简体   繁体   English

将列添加到多个.csv 文件和文件名,因为您将这些.csv 文件组合成单个 dataframe

[英]Adding a column to multiple .csv files with the file name as you combine those .csv files into a single dataframe

I have 50.csv files with over 188k rows combined that I would need to add the file name to so that I am able to track which file it came from.我有 50.csv 文件组合超过 188k 行,我需要添加文件名,以便能够跟踪它来自哪个文件。 I have included the code I am using below which is able to combine the files into a single df.我在下面包含了我正在使用的代码,它能够将文件组合成一个 df。

df = pd.DataFrame()
for file in files:
    if file.endswith('.csv'):
        df=df.append(pd.read_csv(file), ignore_index=True)
df.head()

You're almost there.您快到了。 Instead of appending directly the result of the read_csv() , store it and add a new column with the file name不要直接附加read_csv()的结果,而是存储它并添加一个带有文件名的新列

for file in files:
    if file.endswith('.csv'):
        df_new = pd.read_csv(file)
        df_new['from_file'] = file
        df = df.append(df_new, ignore_index=True)

Also if your file variable is actually the whole path to the file, you can use os.path.basename(file) which return the name of the file only, without the path.此外,如果您的file变量实际上是文件的整个路径,则可以使用os.path.basename(file)仅返回文件名,而不返回路径。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将多个 csv 文件按列与 header 作为文件名组合 - Combine multiple csv files column wise with the header as file name 将来自不同文件夹的多个csv文件中的选定列合并到单个csv文件中 - Combine selected column from multiple csv files from different folders to a single csv file Select 来自多个 csv 文件的特定列,然后使用 pandas 将这些列合并到单个文件中 - Select specific column from multiple csv files, then merge those columns into single file using pandas 将仅一个值(例如:实验条件名称)的单列添加到单个文件夹中的多个csv文件 - Adding a single column of only one value( eg: Experiment condition name) to multiple csv files in a single folder 如何在条件下将csv文件合并到单个文件并将文件名添加为列? - How to merge csv files onto a single file on condition and adding file name as a column? 合并多个csv文件 - Combine multiple csv files 将多个CSV文件中的列合并为一个文件,并使用for循环制作多个CSV文件 - Combine columns from several CSV files into a single file and making multiple CSV file with for loop 将多个 csv 文件读入单个 DataFrame - Reading multiple csv files into single DataFrame Import multiple csv files into pandas and concatenate into one DataFrame where 1st column same in all csv and no headers of data just file name - Import multiple csv files into pandas and concatenate into one DataFrame where 1st column same in all csv and no headers of data just file name 如何将共享同一列的多个 CSV 文件合并到一个新的 CSV 文件中? - How can I combine multiple CSV files that share an identical column into a new CSV file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM