简体   繁体   English

如何使用Python合并多个CSV文件中的列

[英]How to merge columns from multiple CSV files using Python

may be the answer of this question is available but I could not get proper solution and thus I am looking for the perfect solution. 可能是这个问题的答案可用,但我无法获得适当的解决方案,因此我正在寻找理想的解决方案。 Suppose I have multiple CSV files (around 1500) having single column with some time series data (10,000 times or rows). 假设我有多个CSV文件(大约1500个),其中包含具有一些时间序列数据(10,000次或行)的单列。 The column header name is same in all CSV files. 所有CSV文件中的列标题名称均相同。 Suppose I have CSV files like: 假设我有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

My codes are not working and giving something else: 我的代码无法正常工作,并给出了其他提示:

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')

If someone can help in this? 如果有人可以帮助您?

You can try it the following way with a little help from numpy 您可以在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=',')

Use pandas concat function 使用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))

One of the ways to achieve this is by creating another CSV file by merging data from existing CSV files (assuming you have the CSV files in the format aa##.csv )... 实现此目的的方法之一是通过合并现有CSV文件中的数据来创建另一个CSV文件(假设您拥有aa##.csv格式的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()

You can then open & display this file as you wish using pandas. 然后,您可以使用熊猫打开并显示此文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过Python中的多个列将2个CSV文件合并在一起 - How to merge 2 CSV files together by multiple columns in Python Python csv合并具有不同列的多个文件 - Python csv merge multiple files with different columns 如何使用Python Pandas合并多个CSV文件 - How to merge multiple CSV files using Python Pandas 将多个 csv 文件中的几列合并到一个 csv 文件中 - Merge several columns from multiple csv files to one csv file 使用writerow在python错误中合并具有不同列的多个csv文件 - Merge multiple csv files with different columns in python error with writerow Python在多列和最近的日期时间上合并两个csv文件 - Python merge two csv files on multiple columns and nearest datetime 使用 python Z3A43B4F88325D94022C0EFA9C2FA2 库合并连接 2 个具有多个 null 值列的 csv 文件 - Merge join 2 csv files with multiple null values columns using python pandas librery 如何使用 python 或 jq 将多个具有统一列的 JSON 文件合并到一个 CSV 中? - How do I use python or jq to merge multiple JSON files with uniform columns into one CSV? 如何将多个 csv 文件合并到一个文件中,其中 pandas、python 上有特定列? - How to merge multiple csv files into one file with specific columns on pandas, python? Select 来自多个 csv 文件的特定列,然后使用 pandas 将这些列合并到单个文件中 - Select specific column from multiple csv files, then merge those columns into single file using pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM