【问题标题】:How to concatenate for the right side in one file all the .csv files of a directory with python?如何用python在一个文件中连接一个目录的所有.csv文件的右侧?
【发布时间】:2015-05-03 06:51:21
【问题描述】:

我有一个包含 .csv 文件的文件夹,所有文件的 id 相同但内容不同,如下所示:

文件一:

id, content
jdhfs_SDGSD_9403, bla bla bla bla
aadaaSDFDS__ASdas_asad_342, bla bla
...
asdkjASDAS_asdasSFSF_sdf, bla bla

文件二:

id, content
jdhfs_SDGSD_9403, string string string
aadaaSDFDS__ASdas_asad_342, string string string
...
asdkjASDAS_asdasSFSF_sdf, string string string

我想保留 id 列,但将内容合并到一个新文件中,如下所示(即生成一个新文件):

id, content
jdhfs_SDGSD_9403, bla bla bla bla string string string
aadaaSDFDS__ASdas_asad_342, bla bla string string string
...
asdkjASDAS_asdasSFSF_sdf, bla bla string string string

这是我尝试过的:

from itertools import izip_longest
with open('path/file1.csv', 'w') as res, \
        open('/path/file1.csv') as f1,\
        open('path/file1.csv') as f2:
    for line1, line2 in izip_longest(f1, f2, fillvalue=""):
        res.write("{} {}".format(line1.rstrip(), line2))

这样做的问题是将所有内容合并到一行中。知道如何以更 Python 的方式做到这一点吗?

编辑:

import pandas as pd

df1= pd.read_csv('path/file1.csv')
df2=pd.read_csv('path/file2.csv')    

new_df = pd.concat([df1, df2], axis=1)
print new_df


new_df.to_csv('/path/new.csv')

然后标题合并如下:

,id,content,id,content

还有这样的内容:

0jdhfs_SDGSD_9403, bla bla bla bla jdhfs_SDGSD_9403, string string string

我怎样才能得到这样的东西?:

jdhfs_SDGSD_9403, bla bla bla bla string string string

没有数据帧的索引号?

【问题讨论】:

    标签: python python-2.7 csv pandas glob


    【解决方案1】:

    使用 pd.read_csv(FILE) 读取 csvs

    然后这样做:

    import pandas as pd
    pd.concat([df1, df2], axis=1)
    

    或者合并它们(pd.merge())

    看到这个问题:

    Combine two Pandas dataframes with the same index

    【讨论】:

    • 感谢您的帮助。 pandas 可以生成新文件吗?
    • @johndoe YOURDF.to_csv('filename.csv')
    • 感谢您的支持,您知道如何从新文件中删除数据帧的索引号吗?
    • @johndoe 查看 reset_index 和 set_index 方法。
    • 我试过这个:new_df = pd.concat([df1['content'], df2['content']], axis=1) new_df.reset_index(drop=True) new_df['content'].to_csv('path/new.csv') 但索引号仍在新文件中,感谢您的反馈!
    【解决方案2】:

    使用csv standard python module

    import csv
    
    with open(filename1) as file1, open(filename2) as file2, open(newname, "w") as newfile:
        csv1 = csv.reader(file1)
        csv2 = csv.reader(file2)
        newcsv = csv.writer(newfile)
    
        header = next(csv1)
        next(csv2) # Skip the header
    
        newcsv.writerow(header)
    
        for row1, row2 in zip(csv1, csv2):
            id, content1 = row1
            id, content2 = row2
            newcsv.writerow((id, " ".join((content1, content2))))
    

    【讨论】:

    • 我得到了这个:` newcsv.write(header) AttributeError: '_csv.writer' object has no attribute 'write' ` 感谢您的帮助。`
    • @johndoe 那应该是作家,对不起。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 2022-01-19
    相关资源
    最近更新 更多