【问题标题】:How to combine multiple csv files based on file name如何根据文件名组合多个csv文件
【发布时间】:2019-11-08 01:21:17
【问题描述】:

我有 1000 多个 csv 文件,我想将 csv 文件名前五位相同的地方合并到一个 csv 文件中。

    input:
    100044566.csv
    100040457.csv
    100041458.csv
    100034566.csv
    100030457.csv
    100031458.csv
    100031459.csv


import pandas as pd
import os
import glob
path_1 =''
all_files_final = glob.glob(os.path.join(path_1, "*.csv"))
names_1 = [os.path.basename(x1) for x1 in all_files_final]
final = pd.DataFrame()

for file_1, name_1 in zip(all_files_final, names_1):
    file_df_final = pd.read_csv(file_1,index_col=False)
    #file_df['file_name'] = name
    final = final.append(file_df_final)
final.to_csv('',index=False)


我使用了上面的代码,但是它将所有文件合并到一个 csv 文件中,我不知道必须根据名称进行选择

所以从上面的输入 输出 1:将前三个 csv 文件合并到一个 csv 文件中,因为文件名的前五位数字相同。

输出 2:将接下来的 4 个文件合并到一个 csv 文件中,因为文件名的前五位数字相同。

【问题讨论】:

  • 您在实现这一目标时遇到了哪些问题?
  • 到目前为止你做了什么?请添加代码
  • 添加了到目前为止我尝试过的代码
  • @我面临基于文件名合并文件的问题

标签: python-3.x pandas numpy pandas-groupby


【解决方案1】:

我建议您以稍微不同的方式解决问题。

这是我的解决方案:

import os
import pandas as pd

files = os.listdir('.') # returns list of filenames in current folder
files_of_interest = {} # a dictionary that we will be using in future

for filename in files: # iterate over files in a folder
    if filename[-4:] == '.csv': # check whether a file is of .csv format
        key = filename[:5] # as you've mentioned in you question - first five characters of filename is of interest
        files_of_interest.setdefault(key,[]) #if we dont have such key - .setdefault will create such key for us and assign empy list to it
        files_of_interest[key].append(filename) # append to a list new filename

for key in files_of_interest: 
    buff_df = pd.DataFrame()
    for filename in files_of_interest[key]:
        buff_df= buff_df.append(pd.read_csv(filename)) # iterate over every filename for specific key in dictionary and appending it to buff_df
    files_of_interest[key]=buff_df # replacing list of files by a data frame

此代码将创建一个数据框字典。字典的键将是 .csv 文件的一组第一个唯一字符。

然后您可以遍历字典的键以将每个相应的数据帧保存为 .csv 文件。

希望我的回答有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    相关资源
    最近更新 更多