gpt4 book ai didi

python - 使用 groupby 时 Pandas 中的计算模式

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:08 25 4
gpt4 key购买 nike

我有一个表格如下:

Col1 | Col2 | Col3
AAA | 1 | a
AAA | 1 | a
AAA | 1 | b
AAA | 2 | b
AAA | 2 | b
AAA | 2 | b
AAA | 3 | a
BBB | 1 | b
BBB | 1 | b

我想分两步缩小表格:

  1. 在 Col3 中找到与 (Col1, Col2) 值对对应的最常出现的值。

  2. 从step1的结果中,只保留Col1值对应出现频率最高的值。

将步骤 1 应用于上表:(AAA, 1)对应的众数(或最常出现的值)为a,依此类推。我们得到:

Col1 | Col2 | newCol1
AAA | 1 | a
AAA | 2 | b
AAA | 3 | a
BBB | 1 | b

将步骤 2 应用到此表,我们看到 a 是对应于 AAA 的模式,而 b 是对应于BBB - 所以我们得到:

Col1 | newCol2
AAA | a
BBB | b

最佳答案

让我们一行完成

df.groupby(['Col1','Col2']).Col3.apply(pd.Series.mode).\ 
groupby(level=0).apply(pd.Series.mode)
Out[136]:
Col1
AAA 0 a
BBB 0 b
Name: Col3, dtype: object

纯属娱乐

pd.crosstab([df.Col1,df.Col2],df.Col3).idxmax(1).groupby(level=0).apply(pd.Series.mode)
Out[140]:
Col1
AAA 0 a
BBB 0 b
dtype: object

关于python - 使用 groupby 时 Pandas 中的计算模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54848357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com