[英]Append multiple CSVs with the name of the name of each CSV in all rows - Python
[英]How to concatenate all CSVs in a directory, adding CSV name as a column with Python
Downloads/challenges
)。 azerbaijan_challenge_entrants.csv
。 我想创建一个新的CSV( all_entrants.csv
),其中包括所有100个CSV的所有数据,并添加一列新内容: challenge
,其中应包括行数据来自的CSV的名称。
我通常喜欢Python这样的任务。 但是我正在努力使这项工作。 任何帮助,将不胜感激!
使用标准库和3rd party库pandas
os
可以实现:
import os
import pandas as pd
mypath = os.path.join('Downloads', 'challenges')
# get list of files
files = [f for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath, f))]
# build list of dataframes, adding "challenge" column
dfs = [pd.read_csv(os.path.join(mypath, f)).assign(challenge=f) for f in files]
# concatenate dataframes into one
df = pd.concat(dfs, ignore_index=True)
# write to csv
df.to_csv('all_entrants.csv')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.