如何合并csv文件并使用python添加标题行?
问题描述:
我从圣路易斯弗雷德价格指数数据的50 csv
文件,每个文件的格式是这样的:如何合并csv文件并使用python添加标题行?
我想结合多个CSV文件,并添加报头的一个多行他们实现了以下格式:
所以我可以存储在一个CSV文件中的数据,我可以知道有没有什么办法,我可以与Python做呢?
答
DATE
列的重复没有意义。除非有特定的目的。另外,在合并时,要特别注意特定行上的数据属于同一日期。
其更好地利用大熊猫如果你正在使用DATE作为索引合并和使用OUTER法合并。所以,来自同一日期的值是相同的。
import pandas as pd;
df1 = pd.read_table('file1.csv', sep=',')
df2 = pd.read_table('file2.csv', sep=',')
df3 = pd.read_table('file3.csv', sep=',')
因此,基本上加载所有文件作为数据框。然后使用merge
或reduce
函数合并文件。
data_frames = [df1, df2, df3]
你可以在上面的代码添加尽可能多的数据帧。
然后合并它们。为了使属于同一日期值,您需要合并它的DATE
df_merged = reduce(lambda left,right: pd.merge(left,right,on=['DATE'],
how='outer'), data_frames)
然后合并后的数据写入到CSV文件。
pd.DataFrame.to_csv(df_merged, 'merged.txt', sep=',', na_rep='.', index=False)
这应该给你
DATE VALUE1 VALUE2 VALUE3 ....
答
大熊猫是很好的解决方案,但如果你想要一个Python标准库的解决方案:
import csv
from itertools import chain
csv_input_filenames = [
'csvfile1.csv',
'csvfile2.csv',
'csvfile3.csv',
]
csv_output_filename = 'csv_out.csv'
# get the csv data
csv_files = [open(file_name) for file_name in csv_input_filenames]
csv_handles = [csv.reader(csv_file) for csv_file in csv_files]
rows = (list(chain(*row)) for row in zip(*csv_handles))
# write combined output
with open(csv_output_filename, 'wb') as csv_file:
filenames_header = list(chain(
*zip(csv_input_filenames, [''] * len(csv_input_filenames))))
csv_writer = csv.writer(csv_file)
csv_writer.writerow(filenames_header)
for row in rows:
csv_writer.writerow(row)
# close input files
for csv_file in csv_files:
csv_file.close()
答
这将垂直串联中的所有文件提供的目录(所以你不必在代码中指定它们)。这些文件可以有任意数量的列,并且可以处理值中的空格。但是这些文件必须都具有相同的行数。
它只使用模块csv和os。
import os
import csv
dir_base = r'H:\apps\xp\Desktop\localrepo\Temp'
dir_name = '-test2'
output_name = 'output.csv'
path = os.path.join(dir_base, dir_name)
out_path = os.path.join(dir_base, output_name)
def _extend(lines, lineno, line):
try:
lines[lineno].extend(line)
except IndexError:
lines.append(line)
def main():
lines = []
# read and generate new file
for root, dirs, files in os.walk(path):
for f in files:
with open(os.path.join(root, f), 'r') as csvfile:
f_in = csv.reader(csvfile)
for lineno, line in enumerate(f_in, start=1):
if lineno == 1:
header = [''] * len(line)
header[0] = f
_extend(lines, 0, header)
_extend(lines, lineno, line)
# print new file
with open(out_path, 'w', newline='\n') as csvfile:
csv.writer(csvfile).writerows(lines)
if __name__ == '__main__':
main()
如果你的“CSV”文件,有其他的分隔符(因此不是技术上的“C” SV文件),只是改变了代码csv.reader(csvfile)
的这一部分,以指示分隔符,例如,csv.reader(csvfile, delimiter='|')
。
希望它有帮助!
这可以使用Python中的'csv'模块完成。只是谷歌的例子或阅读文档的使用情况。 – sisanared
或者,使用'pandas.read_csv()'读取每个文件,然后将数据帧连接或合并到一个数据帧中。 – DyZ