简体   繁体   中英

Python Append an excel sheet into Pandas-DataFrame

I am trying to create a database and fill it with values gotten from an excel sheet.

My code:

new_db = pd.DataFrame()
workbook = pd.ExcelFile(filename)
df = workbook.parse('Sheet1')
print(df)
new_db.append(df)
print(new_db.head())

But whenever I seem to do this, I get an empty dataframe back.

My excel sheet however is packed with values. When it is printed(print(df)) it prints it out with ID values and all the correct columns and rows.

My knowledge with Pandas-Dataframes is limited so excuse me if I do not know something I should. All help is appreciated.

I think pandas.read_excel is what you're looking for. here is an example:

import pandas as pd

df = pd.read_excel(filename)

print(df.head())

df will have the type pandas.DataFrame
The default parameters of read_excel are set in a way that the first sheet in the excel file will be read, check the documentation for more options(if you provide a list of sheets to read by setting the sheetname parameter df will be a dictionary with sheetnames as keys and their correspoding Dataframes as values). Depending on the version of Python you're using and its distribution you may need to install the xlrd module, which you can do using pip .

You need to reassign the df after appending to it, as @ayhan pointed out in the comments:

new_db = new_db.append(df)

From the Panda's Documentation for append , it returns an appended dataframe, which means you need to assign it to a variable.

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