Python Pandas groupby 后 通过index获取值报错KeyErro
学习pandas时,发现通过index获取groupby操作后的数据报错keyerror,大佬们帮忙看下是什么问题
源代码
import pandas as pd
def pd_account(list_agg,list_group,model):
filename = "datafile/home_account.xlsx"
df = pd.read_excel(filename)
df.columns = ['y','m','d','lsfx','lsje','zffs','lslb','bz','fqr']
list_col = list_group + list_agg
df = df[list_col]
group_df = df.groupby(list_group).agg(model)
print(group_df)
for item in group_df.index:
print(item)
print(group_df[item])
if __name__ == "__main__":
pd_account(['lsje'],['y','lsfx'],'sum')
print(df)
y lsfx lsje
0 2023 + 14334.74
1 2023 - 107.00
.. ... ... ...
169 2023 - 461.00
170 2023 + 461.00
171 2023 - 15.80
[172 rows x 3 columns]
print(group_df
lsje
y lsfx
2023 + 561520.79
- 209005.97
遍历index(print(item))结果
===============================
(2023, '+')
(2023, '-')
通过Index获取值报错
C:\Users\MA110\AppData\Local\Programs\Python\Python311\python.exe E:\OneDrive\MyProject\pythonProject_AppAccount\FunAccount.py
Traceback (most recent call last):
File "C:\Users\MA110\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\indexes\base.py", line 3652, in get_loc
return self._engine.get_loc(casted_key)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "pandas\_libs\index.pyx", line 147, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 176, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 7080, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 7088, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: (2023, '+')
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "E:\OneDrive\MyProject\pythonProject_AppAccount\FunAccount.py", line 14, in <module>
pd_account(['lsje'],['y','lsfx'],'sum')
File "E:\OneDrive\MyProject\pythonProject_AppAccount\FunAccount.py", line 12, in pd_account
print(group_df[item])
~~~~~~~~^^^^^^
File "C:\Users\MA110\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\frame.py", line 3761, in __getitem__
indexer = self.columns.get_loc(key)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\MA110\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\indexes\base.py", line 3654, in get_loc
raise KeyError(key) from err
KeyError: (2023, '+')
进程已结束,退出代码1