【问题标题】:How to merge columns from multiple CSV files using Python如何使用 Python 合并来自多个 CSV 文件的列
【发布时间】:2018-11-29 04:05:49
【问题描述】:

可能是这个问题的答案是可用的,但我无法得到正确的解决方案,因此我正在寻找完美的解决方案。假设我有多个 CSV 文件(大约 1500 个),其中包含单列和一些时间序列数据(10,000 次或行)。所有 CSV 文件中的列标题名称都相同。假设我有 CSV 文件,例如:

aa1.csv      aa2.csv:      aa3.csv:............aa1500.csv:
datavalue   datavalue      datavalue           datavalue
    4            1             1                  2
    2            3             6                  4
    3            3             3                  8                
    4            4             8                  9


I want the output like this:


datavalue,datavalue,datavalue,datavalue,.....datavalue
4,1,1,..2
2,3,6,..4
3,3,3,..8
4,4,8,..9

我的代码不起作用并提供其他内容:

import pandas as pd
import csv
import glob
import os
path 'F:/Work/'
files_in_dir = [f for f in os.listdir(path) if f.endswith('csv')]
for filenames in files_in_dir:
    df = pd.read_csv(filenames)
    df.to_csv('out.csv', mode='a')

如果有人可以帮忙?

【问题讨论】:

  • 每个这样的 CSV 文件是否包含相同数量的
  • 是的,每个 csv 文件都有相同的行数

标签: python python-3.x python-2.7 pandas scipy


【解决方案1】:

实现此目的的方法之一是通过合并现有 CSV 文件中的数据来创建另一个 CSV 文件(假设您的 CSV 文件格式为 aa##.csv)...

contents = []

for filenum in range(2):
    f = open('aa{}.csv'.format(filenum + 1), 'r')
    lines = f.readlines()
    print(lines)
    f.close()

    if contents == []:
        contents = [[] for a in range(len(lines))]

    for row in range(len(lines)):
        contents[row].append(lines[row].rstrip('\n'))
        print(lines[row])

print(contents)
f = open('aa_new.csv', 'w')

for row in range(len(contents)):
    line = str(contents[row])
    line = line.strip('[]')
    f.write(line + '\n')

f.close()

然后,您可以使用 pandas 随意打开和显示此文件。

【讨论】:

  • 在使用 line.strip().splitcan 后出现另一个错误 - 仅将列表(不是“str”)连接到列表
  • 收到这个'22 0.283026666666643 \ N ''21 0.499415555555537 \ N' '20 0.142722222222197 \ N ' '0.0 \ N' '13 0.923109213483146 \ N' '9.08471160493827 \ N' '12 0.864911460674154 \ N” '2.9649911054637865 \ N'
  • 在我有空值的地方给出“'0.0\n'”,在我有值的地方给出“'8.649526419753085\n'”
  • 谢谢@梅尔文
  • 随时@VishalSingh
【解决方案2】:

你可以在 numpy 的帮助下尝试以下方式

import pandas as pd
import numpy as np
import os
path 'F:/Work/'
files_in_dir = [f for f in os.listdir(path) if f.endswith('csv')]
temp_data = []
for filenames in files_in_dir:
    temp_data.append(np.loadtxt(filenames,dtype='str'))

temp_data = np.array(temp_data)
np.savetxt('out.csv',temp_data.transpose(),fmt='%s',delimiter=',')

【讨论】:

  • 正在转储数据但附加值不同
  • 列表中的值与转储的值不同。?这是不可能的
【解决方案3】:

使用pandas concat函数

import pandas as pd
dfs = []
for filenum in range(1,1501):
    dfs.append( pd.read_csv('aa{}.csv'.format(filenum)) )
print(pd.concat(dfs,axis=1).to_csv(index=False))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-16
    • 2015-05-23
    • 2019-11-08
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 2021-06-04
    • 2020-07-22
    相关资源
    最近更新 更多