使用pandas将excel内容转换成字典
使用pandas将excel内容转换成字典
目标
- Excel表格形式
列1 | 列2 | 列3 | 列4 |
---|---|---|---|
值1 | 值2 | 值3 | 值4 |
值5 | 值6 | 值7 | 值8 |
- 获取的目标字典
{'data': [{'列1': '值1', '列2': '值2', '列3': '值3', '列4': '值4'}, {'列1': '值5', '列2': '值6', '列3': '值7', '列4': '值8'}]}
使用pandas读取excel文件
import pandas as pd
def func1(path):
# 创建最终返回的空字典
df_dict = {}
# 读取Excel文件
df = pd.read_excel(path)
# 替换Excel表格内的空单元格,否则在下一步处理中将会报错
df.fillna("", inplace=True)
df_list = []
for i in df.index.values:
# loc为按列名索引 iloc 为按位置索引,使用的是 [[行号], [列名]]
df_line = df.loc[i, ['列1', '列2', '列3', '列4',]].to_dict()
# 将每一行转换成字典后添加到列表
df_list.append(df_line)
df_dict['data'] = df_list
return df_dict