从groupby中的列获取模式

2024-10-01 07:46:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图获取groupby对象中列的模式,但是得到了一个错误:incompatible index of inserted column with frame index。在

这是我要接的线,我不知道怎么修。任何帮助都将不胜感激。在

dfBitSeq['KMeans'] = df.groupby('OnBitSeq')['KMeans'].apply(lambda x: x.mode())

Tags: of对象dfindex错误with模式column
3条回答

你可以看看Attach a calculated column to an existing dataframe。在

这个错误看起来很相似,答案很有用。在

您可以使用下面的^{}.示例。在

from scipy.stats import mode

df = pd.DataFrame([[1, 5], [2, 3], [3, 5], [2, 4], [2, 3], [1, 4], [1, 5]],
                  columns=['OnBitSeq', 'KMeans'])

#    OnBitSeq  KMeans
# 0         1       5
# 1         2       3
# 2         3       5
# 3         2       4
# 4         2       3
# 5         1       4
# 6         1       5

modes = df.groupby('OnBitSeq')['KMeans'].apply(lambda x: mode(x)[0][0]).reset_index()

#    OnBitSeq  KMeans
# 0         1       5
# 1         2       3
# 2         3       5

如果需要将其添加回原始数据帧:

^{pr2}$

Pandas模式返回一个数据帧,不同于mean和median返回标量。所以您只需要使用x.mode().iloc[0]选择切片

dfBitSeq['KMeans'] = df.groupby('OnBitSeq')['KMeans'].apply(lambda x: x.mode().iloc[0])

相关问题 更多 >