python - 合并文件夹中的每个数据框

标签 python csv pandas

我在多个文件夹中有 .csv 文件,如下所示:

文件1

Count    2002_Crop_1   2002_Crop_2   Ecoregion
 20      Corn          Soy           46
 15      Barley        Oats          46

文件2

Count   2003_Crop_1    2003_Crop_2  Ecoregion
24      Corn           Soy          46
18      Barley         Oats         46

对于每个文件夹,我想合并其中的所有文件。

我想要的输出是这样的:

Crop_1  Crop_2 2002_Count  2003_Count  Ecoregion
Corn    Soy    20          24          46
Barley  Oats   15          18          46  

实际上,每个文件夹中有 10 个文件,而不仅仅是 2 个,需要合并。

我现在正在使用此代码:

import pandas as pd, os
#pathway to all the folders
folders=r'G:\Stefano\CDL_Trajectory\combined_eco_folders'
for folder in os.listdir(folders):
    for f in os.listdir(os.path.join(folders,folder)):   
            dfs=pd.read_csv(os.path.join(folders,folder,f))   #turn each file from each folder into a dataframe
            df = reduce(lambda left,right: pd.merge(left,right,on=[dfs[dfs.columns[1]], dfs[dfs.columns[2]]],how='outer'),dfs) #merge all the dataframes based on column location

但这会返回: 类型错误:字符串索引必须是整数,而不是系列

最佳答案

  • 使用glob.globtraverse a directory at a fixed depth .

  • 如果可以的话,尽量避免重复调用 pd.merge。每次调用 pd.merge 都会创建一个新的 DataFrame。因此,每个中间结果中的所有数据都必须复制到新的 DataFrame 中。循环执行此操作会导致 quadratic copying ,这对性能不利。

  • 例如,如果您进行一些列名争论来更改,

    ['Count', '2002_Crop_1', '2002_Crop_2', 'Ecoregion']
    

    ['2002_Count', 'Crop_1', 'Crop_2', 'Ecoregion']
    

    然后您可以使用['Crop_1', 'Crop_2', 'Ecoregion']作为每个DataFrame的索引,并通过一次调用将所有DataFrame组合起来 pd.concat.

<小时/>
import pandas as pd
import glob

folders=r'G:\Stefano\CDL_Trajectory\combined_eco_folders'
dfs = []

for filename in glob.glob(os.path.join(folders, *['*']*2)):
    df = pd.read_csv(filename, sep='\s+')
    columns = [col.split('_', 1) for col in df.columns]

    prefix = next(col[0] for col in columns if len(col) > 1)
    columns = [col[1] if len(col) > 1 else col[0] for col in columns]
    df.columns = columns

    df = df.set_index([col for col in df.columns if col != 'Count'])
    df = df.rename(columns={'Count':'{}_Count'.format(prefix)})

    dfs.append(df)

result = pd.concat(dfs, axis=1)
result = result.sortlevel(axis=1)
result = result.reset_index()
print(result)

产量

   Crop_1 Crop_2  Ecoregion  2002_Count  2003_Count
0    Corn    Soy         46          20          24
1  Barley   Oats         46          15          18

关于python - 合并文件夹中的每个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38678520/

相关文章:

Python Pandas : Compare two CSV files and delete lines from both the file by matching a column

bash - 如何在 Bash 脚本中解析 CSV?

python - 在 i 和 i+1 行条件下创建一个新的标志列?

python - 检索与 pandas 中另一列中元素第一次出现相对应的列中的值 - python

python - 更新数据库中的现有模型

python - 使用 `get_or_create` 时不隐藏软删除实例

python - Windows服务在Anaconda环境中运行?

php - 当我将查询结果导出到 Excel CSV 时,始终显示 HTML 代码

python - 当第二列包含 NaN/空字符串时,连接 pandas 数据框中的两列而不在末尾添加额外的空格

python - 在 2D 数组上创建 4D View 以将其划分为固定大小的单元格