Python3 excel数据读取和写入

初学者:求解答!

目的:从北方分公司2023年商机汇总2月表格的sheet"2月",提取E列值为农业的整行数据。导入到市场数据总表中,sheet"农业"中。

import pandas as pd

# 读取源数据表格
df1 = pd.read_excel('/Users/Administrator/工作/1.J 解决方案部/X项目支撑/北方分公司/北方分公司2023年商机汇总2月.xlsx', sheet_name='2月')

# 提取 E 列值为 '农业' 的整行数据
df2 = df1[df1['E'] == '农业']

# 导入到市场数据总表中的 '农业' sheet
df2.to_excel('/Users/Administrator/工作/1.J 解决方案部/X项目支撑/市场数据总表.xlsx', index=False, sheet_name='农业')


报错信息:

Traceback (most recent call last):
  File "/opt/homebrew/lib/python3.10/site-packages/pandas/core/indexes/base.py", line 3802, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas/_libs/index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 165, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 5745, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 5753, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'E'

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

Traceback (most recent call last):
  File "/Users/Administrator/Desktop/发票/case money all.py", line 7, in <module>
    df2 = df1[df1['E'] == '农业']
  File "/opt/homebrew/lib/python3.10/site-packages/pandas/core/frame.py", line 3807, in __getitem__
    indexer = self.columns.get_loc(key)
  File "/opt/homebrew/lib/python3.10/site-packages/pandas/core/indexes/base.py", line 3804, in get_loc
    raise KeyError(key) from err
KeyError: 'E'
不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

以下答案引用自GPT-3大模型,请合理使用:

。

df1代表的是北方分公司2023年商机汇总2月的数据表,读取之后得到的是一个DataFrame对象。

农业的值在E列,所以要提取这一列的值,可以使用df1[df1['E'] == '农业']这样的语法。

最后,将这一列的数据导入到市场数据总表中,并指定农业sheet的名称。

如果我的回答解决了您的问题,请采纳我的回答