2017-02-23 25 views
1

excel的第一行包含每个单元格中包含\ n字符的单词。 如:转换为csv时,仅从xls的第一行删除 n个字符Python pandas

 
Month "East North Central\n(NSA)" "East North Central\n(SA)" "East South Central\n(NSA)" 

所以在使用这个代码转换为CSV:后\ n为进新线,如

data_xls = pd.read_excel('/home/scripts/usless/HP_PO_hist.xls', 'sheet1', index_col=4,skiprows=3) 
data_xls.to_csv('HH_PO_output.csv', encoding='utf-8') 

它转换的字符:

,Month,"East North Central 
(NSA)","East North Central 
(SA)","East South Central 
(NSA)","East South Central 

但预期产量如:

Month East North Central (NSA) East North Central (SA) East South Central (NSA) East South Central (SA) 

如何在转换为Python df中的csv时仅从此索引行中删除此\ n字符?

+0

其实我试图重现您的示例,但没有问题...可以分享您的原始.xls文件吗? –

回答

3

我用下面的伪数据帧:

import pandas as pd 

columns=["Month", "East North Central\n(NSA)", "East North Central\n(SA)", "East South Central\n(NSA)"] 
df = pd.DataFrame(columns=columns) 

当通过df.to_csv导出到CSV我得到同样的线路中断行为(熊猫0.19.2):此

,Month,"East North Central 
(NSA)","East North Central 
(SA)","East South Central 
(NSA)" 

一种解决方案是简单地用这样的空格替换\n

df.columns = df.columns.str.replace("\n", " ") 

这提供了所需的结果:

,Month,East North Central (NSA),East North Central (SA),East SouthCentral (NSA) 
相关问题