[英]Python append new column from another csv
I generate every days a csv (overwrited) with this two columns(have not headers).我每天都用这两列(没有标题)生成一个 csv(覆盖)。 First is client number and second is the daily sells第一个是客户数量,第二个是每日销售量
963840 3
18065729 2
255657800 4
338082549 183
364915832 2
392633366 14
450647013 3
I need to append in a new csv the daily sells, each day on a new column to know the evolution我需要在每天销售的新 csv 中附加一个新列,以了解演变
963840 3 5 6 20
18065729 2 4 7 8
255657800 4 7
338082549 183 220
364915832 2 5
392633366 14 14
450647013 3 4
thanks in advance提前致谢
I tried to write it symbolic so you can follow the code and load your CSV files and merge them:我试着把它写成符号,这样你就可以按照代码加载你的 CSV 文件并合并它们:
basedf = pd.read_csv('firstday.csv')
days = ['day2.csv','day3.csv','day4.csv','day5.csv']
for day in days:
df = pd.read_csv(day)
basedf = basedf.merge(df,on='clientid',how='left')
Maybe outer join works better if you have different customers in different days.如果您在不同的日子有不同的客户,则外连接可能会更好。
import pandas as pd
day1 = pd.DataFrame({'id': ['963840', '18065729', '255657800', '338082549','364915832','392633366','450647013'],
'day1data': [3,2,4,183,2,14,3]})
day2 = pd.DataFrame({'id': ['963840', '18065729', '255657800', '338082549','364915832','392633366','450647013'],
'day2data': [5,4,7,220,5,14,4]})
print(day1.merge(day2, on='id', how='outer'))
Ant the result will be as below: Ant 结果如下:
id day1data day2data
0 963840 3 5
1 18065729 2 4
2 255657800 4 7
3 338082549 183 220
4 364915832 2 5
5 392633366 14 14
6 450647013 3 4
Also if you want to save as csv, you can use to_csv() method.另外,如果你想保存为 csv,你可以使用to_csv()方法。
day1.merge(day2, on='id', how='outer').to_csv('merged_data.csv',sep=';')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.