【问题标题】:How to concatenate every two csv file from a single folder in to one csv file each?如何将单个文件夹中的每两个 csv 文件连接到一个 csv 文件中?
【发布时间】:2019-08-25 18:32:37
【问题描述】:

我有一个文件夹,其中的文件格式为 p1_1001.csv、p1_1002csv、p2_1001.csv、p2_1002.csv...

它们是单个候选人的第 1 部分和第 2 部分数据 1001,1002...

我想为每个候选人组合 p1 和 p2。也就是说,从存储两个部分的数据的文件夹中为每个候选生成一个 csv 文件。1001,1002,1003..。 所以第一部分是从 1-49 的跟踪编号,第二部分是从 50 到 99。我想在没有 p2 标题的情况下将 PI 与 p2 连接起来。所以在一个文件夹中从试验 1 到 100 获取参与者 1001 的一个 csv 文件

我曾尝试使用 glob,但无法使其正常工作。有人可以帮我解决这个问题吗?

【问题讨论】:

  • 你走了多远?您能否分享迄今为止的代码以及您遇到的问题?
  • 如何生成“每个候选人的单个 csv”?是否只是通过连接 csv 内容? csv的内容重要吗?例如如果 p1_1001.csv 和 p2_1001.csv 都包含 header,那么最终的 1001.csv 是否需要最多包含一个 header?
  • 所以第一部分是从 1 到 49 的轨迹编号,第二部分是从 50 到 99。我想在没有 p2 标题的情况下将 PI 与 p2 连接起来。所以从参与者 1001 获取一个 csv 文件在一个文件夹中试用 1 到 100。@AdityaSantoso

标签: python database pandas dataframe concatenation


【解决方案1】:

我已经使用 glob 进行了尝试,它应该可以正常工作。

import pandas as pd
import glob

_candidates = ['1001', '1002'] # All candidates
_candidate_files = [(candidate, glob.glob('./*{}.csv'.format(candidate))) for candidate in _candidates]

for candidate in _candidate_files:
    df = []
    for file in candidate[1]:
        file_df = pd.read_csv(file)
        df.append(file_df)
    df = pd.concat(df, axis=0)
    df.to_csv(candidate[0] + '.csv')

对于您想要最终 df 的所有候选人,填充列表。这是ofcource 假设p1p2 有对齐的列。

【讨论】:

    【解决方案2】:

    这里有一些想法:

    from os import listdir
    from os.path import isfile, join
    
    # step 1: list all csv in that directory
    mypath = './foo/bar' # this should point to the directory where the csv resides
    csvs = [f for f in listdir(mypath) if ('csv' in f and  isfile(join(mypath, f)))]    
    
    # step 2: group CSVs that belong to one candidate
    groups = {}
    for c in csvs:
        (pNum, candidate) = c.split('_')
        if candidate not in groups:
            groups[candidate] = []
        groups[candidate].append(c)
    
    
    # step 3: read contents for each group, append to one file
    for candidate in groups:
        files = groups[candidate]        
        for f in files:
            with open(join(mypath, f) , 'r') as file:
                data = file.read()
    
            with open(candidate, 'a+') as outFile:                                
                outFile.write(data)
                # if you need to append newline at the end of every segment:
                outFile.write('\n')                
    
    

    附录:如果使用pandas 不是问题,我强烈建议将pandas.read_csv 视为处理csv 的相对轻松且无忧无虑的方式。如果你在pandasDataFrame内操作,你也可以做pd.concat([df1, df2])(docs here)逻辑连接csv内容

    【讨论】:

      猜你喜欢
      • 2021-05-27
      • 2022-01-19
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      • 2021-08-17
      • 2021-04-17
      相关资源
      最近更新 更多