简体   繁体   English

Python将Excel表格添加到Pandas-DataFrame中

[英]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. 我正在尝试创建一个数据库,并用从Excel工作表中获取的值填充它。

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. 但是我的Excel工作表挤满了价值观。 When it is printed(print(df)) it prints it out with ID values and all the correct columns and rows. 打印(print(df))时,将使用ID值以及所有正确的列和行将其打印出来。

My knowledge with Pandas-Dataframes is limited so excuse me if I do not know something I should. 我对Pandas-Dataframes的了解有限,因此,如果我不知道应该知道的内容,请原谅。 All help is appreciated. 感谢所有帮助。

I think pandas.read_excel is what you're looking for. 我认为pandas.read_excel是您想要的。 here is an example: 这是一个例子:

import pandas as pd

df = pd.read_excel(filename)

print(df.head())

df will have the type pandas.DataFrame df将具有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). 设置read_excel的默认参数的方式是,将读取excel文件中的第一张图纸,请查阅文档以获取更多选项(如果通过设置sheetname参数提供了要读取的图纸列表,则df将是带有sheetnames的字典作为键,并将其对应的数据框作为值)。 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 . 根据您使用的Python版本及其发行版,您可能需要安装xlrd模块,您可以使用pip进行安装。

You need to reassign the df after appending to it, as @ayhan pointed out in the comments: 正如@ayhan在评论中指出的那样,您需要在附加到df之后重新分配df:

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. 熊猫的append文档中 ,它返回一个附加的数据框,这意味着您需要将其分配给变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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