【发布时间】:2015-10-02 14:26:07
【问题描述】:
我有三个这样的.csv文件,它们都有相同的id和相同的tag,但不同的text:
.csv 文件一:
id,text
ID_one_111,some text_1
...
ID_n-th_n,some text_n
.csv 文件二
id,text,tag
ID_one_111,some different text_1
...
ID_n-th_n,some different text_n
还有一个像这样的tags 文件
id,tag
ID_one_111,1
...
ID_n-th_n,5
但是,我想生成一个新的 csv 文件,其中包含 text 列和 tags 的串联,如下所示:
id,text,tag
ID_one_111,some text_1 some different text_1,3
...
ID_n-th_n,some text_n some different text_n,5
为此,我使用pandas如下,这是我实际尝试过的:
# -- coding: utf-8 --
import pandas as pd
pd.set_option('display.max_rows', 3000)
df1=pd.read_csv('path/of/the/first/file.csv')
df2=pd.read_csv('path/of/the/second/file.csv').drop('id',1)
label = pd.read_csv('path/of/the/tag_file/tags.csv').drop('id',1)
new_df = pd.concat([df1,df2, label], axis=1)
new_df.reset_index(drop=True)
new_df.to_csv('path/of/the/new/file.csv',
sep=',', encoding='utf-8', index=False)
这种方法的问题是我得到了这样的东西:
id,text,text,tag
ID_one_111,some text_1, some different text_1,3
...
ID_n-th_n,some text_n, some different text_n,5
回想一下,我怎样才能修复上述方法并合并 text 列和标记列以获得类似的结果:
id,text,tag
ID_one_111,some text_1 some different text_1,3
...
ID_n-th_n,some text_n some different text_n,5
无论如何,我阅读了to_csv 文档,但没有找到任何“删除分隔符参数”。提前谢谢各位。
更新
感谢@maxymoo 的回答,我尝试了这个:
df_final = pd.DataFrame({'id':new_df.iloc[:,0],
'content':new_df.iloc[:,1] + ' ' + new_df.iloc[:,2],
'label':new_df.iloc[:,3]}).to_csv('new.csv',
sep=',', encoding='utf-8', index=False)
但是文件只是被 id、文本和标签弄得一团糟
【问题讨论】:
标签: python python-2.7 parsing csv pandas