pandas - groupby(熊猫)之后的问题,分组列不可访问
问题描述
groupby 后我遇到问题并收到此错误消息:
回溯(最后一次调用):文件“C:\Users\User\PycharmProjects\HashTag_Curso\venv\lib\site-packages\pandas\core\indexes\base.py”,第 3080 行,在 get_loc 返回 self._engine。 get_loc(casted_key) 文件“pandas_libs\index.pyx”,第 70 行,在 pandas._libs.index.IndexEngine.get_loc 文件“pandas_libs\index.pyx”,第 101 行,在 pandas._libs.index.IndexEngine.get_loc 文件中“ pandas_libs\hashtable_class_helper.pxi”,第 4554 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item 文件“pandas_libs\hashtable_class_helper.pxi”,第 4562 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 'Ano'
上述异常是以下异常的直接原因:
回溯(最后一次调用):文件“C:/Users/User/PycharmProjects/Bibliotecas/Exemplo.py”,第 11 行,在 x = dfg['Ano'] 文件“C:\Users\User\PycharmProjects\HashTag_Curso \venv\lib\site-packages\pandas\core\frame.py",第 3024 行,在getitem indexer = self.columns.get_loc(key) 文件“C:\Users\User\PycharmProjects\HashTag_Curso\venv\lib\ site-packages\pandas\core\indexes\base.py",第 3082 行,在 get_loc 中从 err KeyError: 'Ano' 中引发 KeyError(key)
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
from astropy.stats import biweight_midcorrelation as bw_cor
df = pd.read_csv(r'Bases_dados\D_1_4M\Tudo/combined.csv').iloc[:100000]
df['Ano'] = df['Data decimal']//1
dfg = df.groupby(by=["Ano"]).mean()
print(dfg)
x = dfg['Ano']
y = dfg['Lances']
r = np.corrcoef(x, y)[0][1]
bwr = bw_cor(x, y)
print(bwr, r)
plt.scatter(x, y)
plt.show()
如果我使用 x = df['Ano'] y = df['Lances']
工作正常,但使用 dfg(按“Ano”分组),我收到那个错误消息。
当我打印(dfg)时,“Ano”列正常显示。
解决方案
它已移至索引部分,因此您可以reset_index
或传递as_index=False
给 groupby 以开始:
dfg = df.groupby(by="Ano", as_index=False).mean()
推荐阅读
- javascript - 未填写、未选中或未选中输入字段时,如何显示错误消息?
- python - 如何使用 Python 遍历一个基本网站以创建 URL 列表,然后打印每个 URL 的文本
- dicom - 如何确定 Mammo 图像是 MLO 还是 CC?
- wordpress - 用 htaccess 重写 URL 整个页面不包括 404 错误主页
- java - 使用 MapStruct 忽略 DTO 字段(Spring boot)
- python - Numpy hstack 给出位置参数错误
- python - 为什么我收到错误“系统找不到指定的路径”。在子进程 python
- python - Matplotlib - 将图例放在图下方并靠近图形边缘
- javascript - 使用 react-onclickoutside 使模式按钮消失的问题(仅限手机)
- python - Pygame曲线运动问题如何解决?