Search code examples
pythonpandasglob

Getting a TypeError: list indices must be integers or slices, not str


I´m pretty new at python , cant seem to get this code to work , getting a "TypeError: list indices must be integers or slices, not str," --help please ! Thanks a ton

import pandas as pd 
from glob import glob
filenames = glob('abc*.xls')
df3 =[pd.read_excel(f) for f in filenames]
df4 = df3[df3['Unnamed: 11'].str.contains("tele", na=False)]

Solution

  • Here df3 is list of DataFrames, because created by list comprehension.

    So you can join all DataFrames together if possible:

    df3 =[pd.read_excel(f) for f in filenames]
    df33 = pd.concat(df3, ignore_index=True)
    df4 = df33[df33['Unnamed: 11'].str.contains("tele", na=False)]
    

    Another idea is processing each DataFrame separately:

    for df in df3:
        df4 = df3[df3['Unnamed: 11'].str.contains("tele", na=False)]
        ...
        ...