I have .csv
files within multiple folders which look like this:
File1
Count 2002_Crop_1 2002_Crop_2 Ecoregion
20 Corn Soy 46
15 Barley Oats 46
File 2
Count 2003_Crop_1 2003_Crop_2 Ecoregion
24 Corn Soy 46
18 Barley Oats 46
for each folder I want to merge all of the files within.
My desired output would be something like this:
Crop_1 Crop_2 2002_Count 2003_Count Ecoregion
Corn Soy 20 24 46
Barley Oats 15 18 46
In reality there are 10 files in each folder, not just 2, that need to be merged.
I am using this code as of now:
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
but this returns:
TypeError: string indices must be integers, not Series