【问题标题】:How to drop the separator when concatenating two csv files with pandas?将两个csv文件与熊猫连接时如何删除分隔符?
【发布时间】: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


    【解决方案1】:

    这是一个解决方案,尽管没有使用 pandas:

    import csv
    from collections import defaultdict
    
    rows = defaultdict(list)
    
    for csv in ['csv_one.csv', 'csv_two.csv', 'csv_three.csv']:
        with open(csv) as f:
            next(f) # skips the header row
            reader = csv.reader(f, delimiter=',')
            for row in reader:
                rows[row[0]].append(row[1:])
    
    with open('out.csv', 'w') as f:
        writer = csv.writer(f, delimiter=',')
        for k,v in rows.iteritems():
             writer.writerow([k]+v)
    

    【讨论】:

    • 非常优雅,Pandas 在这个问题上肯定是矫枉过正。
    【解决方案2】:

    我认为解决此问题的最佳方法是对您拥有的两列进行矢量化字符串操作。像这样的:

    df_final = pd.DataFrame({'ID':new_df.iloc[:,0], 
                             'text':new_df.iloc[:,1] + ' ' + new_df.iloc[:,2], 
                             'tag':new_df.iloc[:,3]})
    

    此外,您最好确保所有 ID 在您的文件中都对齐,否则您可能需要考虑使用 merge 而不是 concat

    【讨论】:

    • 感谢您的帮助。对不起,但我不明白如何使用上述方法,你能提供一些更详细的例子吗?谢谢!
    【解决方案3】:

    有序字典可用于根据您的第一个文件保留行顺序,如果 3 个 CSV 输入文件没有 100% 排列,它也可以工作。如前所述,Pandas 对于此操作可能有点过头了。

    这 3 个源 CSV 文件中的每一个的标题也会合并到您的输出 CSV 文件中。

    import collections, csv
    
    drows = collections.OrderedDict()
    lheaders = []
    
    for file in ["file_1.csv", "file_2.csv", "file_3.csv"]:
        with open(file, "r") as f_input:
            csv_input = csv.reader(f_input)
            headers = csv_input.next()
            lheaders.extend(headers[1:])
    
            for data_row in csv.reader(f_input):
                drows.setdefault(data_row[0], []).extend(data_row[1:])
    
    with open("output.csv", "wb") as f_output:
        csv_output = csv.writer(f_output)
        csv_output.writerow([headers[0]] + lheaders)
    
        for id, row in drows.items():
            csv_output.writerow([id] + row)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 2016-05-16
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 2012-08-05
      相关资源
      最近更新 更多