简体   繁体   English

如何串联目录中的所有CSV,并使用Python将CSV名称添加为列

[英]How to concatenate all CSVs in a directory, adding CSV name as a column with Python

  • I have a folder with about 100 CSVs ( Downloads/challenges ). 我有一个包含约100 CSV的文件夹( Downloads/challenges )。
  • Each CSV has the same 50+ columns. 每个CSV具有相同的50+列。
  • Each CSV is titled something like azerbaijan_challenge_entrants.csv . 每个CSV的标题都类似于azerbaijan_challenge_entrants.csv

I want to create one new CSV ( all_entrants.csv ) that includes all data from all 100 CSVs, adding one new column: challenge , which should include the name of the CSV that the row data came from. 我想创建一个新的CSV( all_entrants.csv ),其中包括所有100个CSV的所有数据,并添加一列新内容: challenge ,其中应包括行数据来自的CSV的名称。

I generally like Python for tasks like this. 我通常喜欢Python这样的任务。 But I am struggling to make this work. 但是我正在努力使这项工作。 Any help would be appreciated! 任何帮助,将不胜感激!

This is possible with os from the standard library and 3rd party library pandas : 使用标准库和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.

相关问题 在所有行中附加多个CSV,其中包含每个CSV的名称 - Python - Append multiple CSVs with the name of the name of each CSV in all rows - Python 如何使用python将目录中所有.csv文件的右侧连接在一起? - How to concatenate for the right side in one file all the .csv files of a directory with python? 合并文件夹中的所有csv,并在Python中添加带有原始文件名的新列 - Merging all csvs in a folder and adding a new column with filename of original file in Python Python - 将根目录名称与所有子文件夹名称连接起来 - Python - concatenate root directory name with all sub-folder names 读取 csvs,添加一列,将数据放入新列,然后将 csvs 保存在 python 中 - Reading Csvs, adding a column, putting data into the new column and then saving csvs in python 如何使用 python 遍历目录并从所有 csvs 中删除特定列? - How do use python to iterate through a directory and delete specific columns from all csvs? Pyspark:在python中将所有压缩的csv合并为一个csv - Pyspark: Merge all zipped csvs into one csv in python 使用 python 使用文件名信息将列批量插入 CSV - Using python to batch insert a column into CSVs using file name information Python - 在特定目录中连接CSV文件 - Python - Concatenate CSV files in a specific directory Python:如何拆分目录中csv文件的名称 - Python: How to split the name of the csv file in directory
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM