【问题标题】:Combining data of multiple folders合并多个文件夹的数据
【发布时间】:2021-09-18 21:02:42
【问题描述】:

我有两个包含数据的文件 (>10) 文件夹 (Q & P)。我想自动分析文件夹中的所有匹配文件。这意味着 P1 & Q1 , P5 & Q5 等。我没有错误,但我没有得到我想要的结果。我认为这是因为我的循环没有记住中间步骤(仅对文件夹中的最后一个文件进行操作),这是正确的吗?在文件夹的初始循环之后,如何分析所有匹配的文件?非常感谢您的帮助!

p = [] #empty list for results precipiation loop
q = [] #empty list for results discharge loop

#Preciptation folder read 
for root, dirs, files in os.walk(r"C:TSA_P"):
    for filename in files:
        file_path = os.path.join(root, filename)
        with open(file_path) as file:
            file = pd.read_csv(file, delimiter=' ', header=None, skiprows=1, names=['year','month','day','precipitation_cpc'])
            file.columns = file.columns.str.replace(' ', ',')
            file.loc[:,'dt'] = pd.to_datetime(file[['year', 'month', 'day']])
            file.index = file['dt']
            file.columns = ['year', 'month', 'day','Rain','dt']
            p.append(file)
            
#file.head()

#Discharge folder read
for root, dirs, files in os.walk(r"C:\TSA_Q"):
    for filename in files:
        file_path = os.path.join(root, filename)
        with open(file_path) as f:
            f = pd.read_csv(f, delimiter=' ', header=None, skiprows=1, names=['year','month','day','streamflow_m3s', 'qual_control_by_ana', 'qual_flag'])
            f.columns = f.columns.str.replace(' ', ',')
            f.loc[:,'dt'] = pd.to_datetime(f[['year', 'month', 'day']])
            f.index = f['dt']
            f.columns = ['year', 'month', 'day','Discharge','Quality','Flag','dt']
            f = f.loc[(f.index.year>=1980)]
            q.append(file)
#f.head()

#Part C
C = pd.DataFrame() #Data P & Q per catchment
Format = (24*3600) #mm/d to mm/s
C['Psum'] = file['Rain'].resample('Y').sum()/Format #Daily to yearly
C['Qsum'] = f['Discharge'].resample('Y').sum() #Daily to yearly
#C.head()

【问题讨论】:

  • 要做这种事情的第一种方法是在循环之前创建一个空列表,并在循环的每次迭代中添加刚刚计算的元素。那么你有一个所有计算元素的列表。
  • 谢谢,但是我如何才能继续为循环的每个元素执行 C 部分(参见脚本)?我现在已经创建了两个列表(用于 P 和 Q),但是如何让它们在 C 部分中相互交互?

标签: python pandas loops file


【解决方案1】:

我建议使用“替换”。 如果你有每个相同的文件名,替换 P 的路径将找到对 Q 文件。 (例如:C:\TSA_P\1.csv - C:\TSA_Q\1.csv)

如果这不起作用,请告诉我们有关此问题的更多信息。

import os
import pandas as pd

C = pd.DataFrame()  # Data P & Q per catchment
Format = (24 * 3600)  # mm/d to mm/s

# Preciptation folder read
for root, dirs, files in os.walk(r"C:\\TSA_P"):
    for filename in files:
        file_path = os.path.join(root, filename) # file path: P path
        with open(file_path) as file:
            file = pd.read_csv(file, delimiter=' ', header=None, skiprows=1,
                               names=['year', 'month', 'day', 'precipitation_cpc'])
            file.columns = file.columns.str.replace(' ', ',')
            file.loc[:, 'dt'] = pd.to_datetime(file[['year', 'month', 'day']])
            file.index = file['dt']
            file.columns = ['year', 'month', 'day', 'Rain', 'dt']
        # file: content of P

        file_path = file_path.replace('TSA_P', 'TSA_Q') # file path: Q path
        with open(file_path) as f:
            f = pd.read_csv(f, delimiter=' ', header=None, skiprows=1,
                            names=['year', 'month', 'day', 'streamflow_m3s', 'qual_control_by_ana', 'qual_flag'])
            f.columns = f.columns.str.replace(' ', ',')
            f.loc[:, 'dt'] = pd.to_datetime(f[['year', 'month', 'day']])
            f.index = f['dt']
            f.columns = ['year', 'month', 'day', 'Discharge', 'Quality', 'Flag', 'dt']
            f = f.loc[(f.index.year >= 1980)]
        # f: content of Q

        # Part C
        C['Psum'] = file['Rain'].resample('Y').sum() / Format  # Daily to yearly
        C['Qsum'] = f['Discharge'].resample('Y').sum()  # Daily to yearly

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    相关资源
    最近更新 更多