[英]How to concatenate for the right side in one file all the .csv files of a directory with python?
我有一個包含.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
沒有數據幀的索引號?
使用pd.read_csv(FILE)讀取csvs
然后執行以下操作:
import pandas as pd
pd.concat([df1, df2], axis=1)
或合並它們(pd.merge())
看到這個問題:
即
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))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.