简体   繁体   中英

TypeError: cannot concatenate object of type '<class 'dict'>' when trying to concatenate Excel files

My question might be outdated but I'm sure it's not a duplicated one and sorry if it is !

I'm trying to concatenate some Excel files (stored in a folder) by usingpandas.concat but I keep getting errors, like the one shown below:

CODE:

import pandas as pd
import os

def concat_excel(folder, ws=None):

    data = []

    for f in os.listdir(folder):
        current_df = pd.read_excel(os.path.join(folder, f), sheet_name=ws, dtype=str)
        current_df['Filename'] = f.split('.')[0]
        data.append(current_df)

    df = pd.concat(data, axis=0)

    return df

concat_excel(r'test\myfolder')

ERROR:

------> df = pd.concat(data)

TypeError : cannot concatenate object of type '<class 'dict'>'; only Series and DataFrame objs are valid

Do you know how to fix this, please?
Feel free to propose any better way for doing this..
Any help will be appreciated !

I found a workaround !
I'm adding it here, maybe it will be helpful for people who may face the same issue:

import pandas as pd
import os

def concat_excel(folder, ws=None):

    data = []

    for f in os.listdir(folder):
        df = pd.concat(pd.read_excel(os.path.join(folder, f), sheet_name=ws, dtype=str))
        df['Filename'] = f.split('.')[0]

    return df

concat_excel(r'test\myfolder')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM