首页 > 解决方案 > 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”列正常显示。

标签: pandaspandas-groupby

解决方案


它已移至索引部分,因此您可以reset_index或传递as_index=False给 groupby 以开始:

dfg = df.groupby(by="Ano", as_index=False).mean()

推荐阅读