weixin_46635193 2021-12-22 22:57 采纳率: 80%
浏览 108
已结题

请各位看下解决办法——提取EXCEL中的列数据

提取EXCEL中的列数据,列名报错,不清楚究竟哪里错误,请指教
源代码:

import pandas as pd
df_list=pd.read_excel("采购表.xlsx",sheet_name=None)
df_all=pd.concat(df_list.values())
df_names=pd.DataFrame({"物品":list(df_all["采购物品"].unique())})
df_names.to_excel("采购表-物品列表.xlsx", index=False)

报错:

C:\Users\Administrator\Desktop\test\Scripts\python.exe C:/Users/Administrator/Desktop/test/yuyue.py
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\test\lib\site-packages\pandas\core\indexes\base.py", line 3361, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas\_libs\index.pyx", line 76, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 5198, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 5206, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: '采购物品'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\test\yuyue.py", line 4, in <module>
    df_names=pd.DataFrame({"物品":list(df_all["采购物品"].unique())})
  File "C:\Users\Administrator\Desktop\test\lib\site-packages\pandas\core\frame.py", line 3458, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:\Users\Administrator\Desktop\test\lib\site-packages\pandas\core\indexes\base.py", line 3363, in get_loc
    raise KeyError(key) from err
KeyError: '采购物品'

进程已结束,退出代码1


  • 写回答

3条回答 默认 最新

  • 陈年椰子 2021-12-24 12:26
    关注

    按你的excel,这样试试

    df_list = pd.read_excel("采购表.xlsx",sheet_name=None)
    print(df_list)
    df_all=pd.concat(df_list.values())
    df_names=pd.DataFrame({"物品":list(df_all["物品"].unique())})
    df_names.to_excel("采购表-物品列表.xlsx", index=False)
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 1月4日
  • 已采纳回答 12月27日
  • 修改了问题 12月22日
  • 创建了问题 12月22日