Pandas read_excel()–用Python读取Excel文件

时间:2020-02-23 14:42:08  来源:igfitidea点击:

我们可以使用pandas模块的read_excel()函数将Excel文件数据读入DataFrame对象。

如果您查看一张Excel工作表,它是一个二维表。
DataFrame对象还表示二维表格数据结构。

1.Pandas read_excel()示例

假设我们有一个包含两张纸的excel文件-员工和汽车。
第一行包含表的标题。

Excel文件表数据

这是读取"雇员"工作表数据并打印的示例。

import pandas

excel_data_df = pandas.read_excel('records.xlsx', sheet_name='Employees')

# print whole sheet data
print(excel_data_df)

输出:

EmpID    EmpName EmpRole
0      1     hyman     CEO
1      2  David Lee  Editor
2      3   Lisa Ray  Author
  • 第一个参数是excel文件的名称。

  • sheet_name参数定义要从excel文件读取的图纸。

  • 当我们打印DataFrame对象时,输出是一个二维表。
    它看起来类似于Excel工作表记录。

2. Excel工作表的列标题列表

我们可以使用dataframe对象的columns属性获取列标题列表。

print(excel_data_df.columns.ravel())

输出:

['EmpID' 'EmpName' 'EmpRole']

3.打印列数据

我们可以获取列数据并将其转换为值列表。

print(excel_data_df['EmpName'].tolist())

输出:

['hyman', 'David Lee', 'Lisa Ray']

4.Pandas read_excel()usecols示例

我们可以指定要从excel文件读取的列名。
当您只对excel工作表中的几列感兴趣时,此功能很有用。

import pandas

excel_data_df = pandas.read_excel('records.xlsx', sheet_name='Cars', usecols=['Car Name', 'Car Price'])
print(excel_data_df)

输出:

Car Name      Car Price
0      Honda City     20,000 USD
1  Bugatti Chiron  3 Million USD
2     Ferrari 458   2,30,000 USD

5.读取没有标题行的Excel文件

如果Excel工作表没有任何标题行,请将标题参数值传递为None。

excel_data_df = pandas.read_excel('records.xlsx', sheet_name='Numbers', header=None)

如果您将标头值作为整数传递,例如3。
那么第三行将被视为标头行,并且将从下一行开始读取值。
标头行之前的所有数据都将被丢弃。

6. Excel工作表用于Dict,CSV和JSON

DataFrame对象具有多种实用程序方法,可将表格数据转换为Dict,CSV或者JSON格式。

excel_data_df = pandas.read_excel('records.xlsx', sheet_name='Cars', usecols=['Car Name', 'Car Price'])

print('Excel Sheet to Dict:', excel_data_df.to_dict(orient='record'))
print('Excel Sheet to JSON:', excel_data_df.to_json(orient='records'))
print('Excel Sheet to CSV:\n', excel_data_df.to_csv(index=False))

输出:

Excel Sheet to Dict: [{'Car Name': 'Honda City', 'Car Price': '20,000 USD'}, {'Car Name': 'Bugatti Chiron', 'Car Price': '3 Million USD'}, {'Car Name': 'Ferrari 458', 'Car Price': '2,30,000 USD'}]
Excel Sheet to JSON: [{"Car Name":"Honda City","Car Price":"20,000 USD"},{"Car Name":"Bugatti Chiron","Car Price":"3 Million USD"},{"Car Name":"Ferrari 458","Car Price":"2,30,000 USD"}]
Excel Sheet to CSV:
 Car Name,Car Price
Honda City,"20,000 USD"
Bugatti Chiron,3 Million USD
Ferrari 458,"2,30,000 USD"