【问题标题】:Concatenate csv files with condition用条件连接 csv 文件
【发布时间】:2023-03-27 22:05:01
【问题描述】:

我想以尽可能快的方式将多个 csv 文件与列值的条件连接起来。

我有一些有效的代码,但是在我将数据帧减少到我需要的站点之前,它会连接所有 csv 文件的所有行(通过station_number 列中的值)。我想先选择我需要的行,然后再进行连接,这样可以提高运行时间。感谢您的任何建议!

station = int(input("station number? ")) 

def Datastations (station,path): 
    filepaths = [os.path.join(path, f) for f in listdir(path) if f.endswith('.csv')]
    df = pd.concat(map(pd.read_csv, filepaths)) 
    df = df[df.station_number==station]
    return (df)

df1 = Datastations(station,"refdata/obs") 
df2 = Datastations(station,"refdata/BoM_ETA_20160501-20170430/obs")

【问题讨论】:

    标签: python pandas csv concatenation


    【解决方案1】:

    你没有说你遇到了什么麻烦,所以我只能为你重新排序:

    import pandas as pd
    import os
    
    def Datastations (station,path): 
        filepaths = [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.csv')]
        def process_csv(file_name):
            df = pd.read_csv(file_name)
            return df[df.station_number==station]
        return pd.concat(map(process_csv, filepaths))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-13
      • 2020-07-20
      • 2020-11-03
      • 2014-11-10
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      相关资源
      最近更新 更多