[英]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.