【问题标题】:How to merge CSVs horizontally + avoid using commas to split pandas df如何水平合并 CSV + 避免使用逗号分割 pandas df
【发布时间】:2021-10-01 04:46:27
【问题描述】:

我有大约 1000 多个 CSV 需要水平合并。这是我的代码:

import os
import glob
import pandas as pd

dirname = r'path'
os.listdir(dirname)



extension = 'csv'

all_filenames = [i for i in glob.glob('*.{}'.format(extension))]

dflist = []
for file in all_filenames:
    df = pd.read_csv(dirname+file, header=None, sep='\n')
    print(df)
    df = df[0].str.split(',', expand=True)
    dflist.append(df)

result = pd.concat(dflist, axis=1)
file_name = r'newfilenamepath'
result.to_csv(file_name)

问题是数据包括“Bob's Company, Ltd”之类的项目,这些项目最终会分成两列:“Bob's Company”和“Ltd”,因为我是根据逗号进行拆分的。用逗号以外的任何东西分割会导致一些非常时髦的格式。所涉及的 CSV 没有相同的标题、列数或行数。我只是想把它们放在一起。

如果相关,我设法编写代码将它们垂直合并,我可能需要进行简单的编辑才能将它们水平合并:

Dir = r'path'
files = os.listdir(Dir)
file_name = 'mergedcsvfilename'
with open(file_name + '.csv','w') as wf:
    for file in files:
        if '.DS_Store' not in file:
            with open(Dir + file) as rf:
                for line in rf:
                    if line.strip(): # if line is not empty
                        if not line.endswith("\n"):
                            line+="\n"
                        wf.write(line)

【问题讨论】:

  • 如果逗号用作数据字段分隔符并且出现在数据字段中,我看不到判断逗号是否为分隔符的方法。字符串值是否包含在引号中?你能举一个你的输入数据的例子吗?
  • pd.read_csv 使用quotechar='"' 选项?
  • 请从您的 CSV 文件中以文本格式添加几行到您的问题中。如果逗号在引号内,通常会自动忽略它们。
  • 您是否需要匹配文件中的行,或者您是否正在寻找一个简单的水平合并,即 line1 与 line1、2 与 2 等等...

标签: python pandas csv


【解决方案1】:

在不使用 pandas 的情况下水平合并它们

Dir = r'path'
files = [ open(f.name,"r") for f in os.scandir(Dir) if f.is_file() and '.DS_Store' not in f.name ]
with open(file_name + '.csv','w') as wf:
    while True:
        r = ','.join([f.readline().rstrip('\n') for f in files])
        if not r.rstrip(','): break
        wf.write(r)

map(lambda f: f.close(), files)

这假设所有文件都具有相同的行数和相同的列数

【讨论】:

    猜你喜欢
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 2021-08-23
    • 1970-01-01
    • 2022-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多