0

I am trying to read a series of xls files in a loop and create a master dataframe. While all files have same columns, in some files, a column is a string while in others, it is int. I want to read all of it as string to prevent any problems. Pandas read the first file, but all the others show up as Nan,NaT in my dataframe. What did I do wrong?

for f in glob.glob("C:\Consoildated_DailyReports\Hold*.xlsx"):
    df = pd.read_excel(f,sheet_name='Data')
    df = df.astype(str)
    #df.to_html()
    data1 = data1.append(df,ignore_index=True)

data1

1 Answer 1

4

pd.read_excel(..., dtype={"col_name": object}) can do it! This is an argument that lets you specify how pandas reads the data type as it reads.

for f in glob.glob("C:\Consoildated_DailyReports\Hold*.xlsx"):
    df = pd.read_excel(f,sheet_name='Data', dtype={"col_name": object})
    df = df.astype(str)
    #df.to_html()
    data1 = data1.append(df,ignore_index=True)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Still does not work. And when I try to write the final data1 to an excel, I only get the result of reading the first file.
Is the glob properly populating?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.