两个使用 Pandas 读取异常数据结构 Excel 的方法,拿走不谢!
扫描二维码
随时随地手机看文章
![两个使用 Pandas 读取异常数据结构 Excel 的方法,拿走不谢!](/images/21ic_nopic.gif)
![两个使用 Pandas 读取异常数据结构 Excel 的方法,拿走不谢!](/images/21ic_nopic.gif)
![两个使用 Pandas 读取异常数据结构 Excel 的方法,拿走不谢!](/images/21ic_nopic.gif)
![两个使用 Pandas 读取异常数据结构 Excel 的方法,拿走不谢!](/images/21ic_nopic.gif)
指定列读取
一般情况下,我们使用 read_excel 函数读取 Excel 数据时,都是默认从第 A 列开始读取的,但是对于某些 Excel 数据,往往不是从第 A 列就有数据的,此时我们需要参数 usecols 来进行规避处理比如上面的 Excel 数据,如果我们直接使用 read_excel(src_file) 读取,会得到如下结果![两个使用 Pandas 读取异常数据结构 Excel 的方法,拿走不谢!](/images/21ic_nopic.gif)
src_file = Path.cwd() / 'shipping_tables.xlsx'
df = pd.read_excel(src_file, header=1, usecols='B:F')
![两个使用 Pandas 读取异常数据结构 Excel 的方法,拿走不谢!](/images/21ic_nopic.gif)
也可以通过列名称来选择所需的列数据df = pd.read_excel(
src_file,
header=1,
usecols=['item_type', 'order id', 'order date', 'state', 'priority'])
这种做法在列的顺序改变但是列的名称不变的时候非常有用最后,usecols 还可以接受一个可调用的函数def column_check(x):
if 'unnamed' in x.lower():
return False
if 'priority' in x.lower():
return False
if 'order' in x.lower():
return True
return True
df = pd.read_excel(src_file, header=1, usecols=column_check)
该函数将按名称解析每一列,并且必须为每一列返回 True 或 False当然也可以使用 lambda 表达式cols_to_use = ['item_type', 'order id', 'order date', 'state', 'priority']
df = pd.read_excel(src_file,
header=1,
usecols=lambda x: x.lower() in cols_to_use)
范围和表格
在某些情况下,Excel 中的数据可能会更加不确定,在我们的 Excel 数据中,我们有一个想要读取的名为 ship_cost 的表,这该怎么获取呢![两个使用 Pandas 读取异常数据结构 Excel 的方法,拿走不谢!](/images/21ic_nopic.gif)
import pandas as pd
from pathlib import Path
src_file = src_file = Path.cwd() / 'shipping_tables.xlsx'
wb = load_workbook(filename = src_file)
查看所有的 sheet 页,获取某个 sheet 页,获取 Excel 范围数据wb.sheetnames
sheet = wb['shipping_rates']
lookup_table = sheet.tables['ship_cost']
lookup_table.ref
![两个使用 Pandas 读取异常数据结构 Excel 的方法,拿走不谢!](/images/21ic_nopic.gif)
data = sheet[lookup_table.ref]
rows_list = []
# 循环获取数据
for row in data:
cols = []
for col in row:
cols.append(col.value)
rows_list.append(cols)
df = pd.DataFrame(data=rows_list[1:], index=None, columns=rows_list[0])
![两个使用 Pandas 读取异常数据结构 Excel 的方法,拿走不谢!](/images/21ic_nopic.gif)
![两个使用 Pandas 读取异常数据结构 Excel 的方法,拿走不谢!](/images/21ic_nopic.gif)