我在多个文件夹中有.csv
个文件,如下所示:
文件1
Count 2002_Crop_1 2002_Crop_2 Ecoregion
20 Corn Soy 46
15 Barley Oats 46
文件2
^{pr2}$对于每个文件夹,我要合并其中的所有文件。在
我想要的输出是这样的:
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
但这会带来:
TypeError: string indices must be integers, not Series
使用
glob.glob
到{a1}。如果可以的话,尽量避免重复调用
pd.merge
。对pd.merge
的每次调用都会创建一个新的数据帧。因此,每个中间结果中的所有数据都必须复制到新的数据帧中。在循环中执行此操作会导致quadratic copying,这对性能不利。例如,如果您要更改列名
到
^{pr2}$然后,您可以使用的调用结合起来。
['Crop_1', 'Crop_2', 'Ecoregion']
作为每个数据帧的索引,并将所有数据帧与一个对^{收益率
相关问题 更多 >
编程相关推荐