python - 如何分组并计算 Pandas 的概率

标签 python pandas

我有一个数据框如下

id1, id2, thumb_up
 1,  1,   1
 1,  2,   -1
 1,  3,   1
 2, 1,   1
 2,  3,  -1
and so on

我想创建以下数据框

id1, thumb_up_prob
 1, 0.66 ( 2 positive feedback and 1 negative = 2/3)
 2, 0.5 (1 positive and 1 negative feedback = 1/2)

等等.. 所以基本上我想 groupby id1 并计算概率。 我如何在 Pandas 中做到这一点。

最佳答案

  • 检查 df.thumb_up 是否等于 1
  • groupby df.id1
  • 因为 boolint 的子集,我们调用 mean

df.thumb_up.eq(1).groupby(df.id1).mean()

关于python - 如何分组并计算 Pandas 的概率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43014944/

相关文章:

python - 根据百分比列合并列

python - 从嵌套字典创建 dfs 并计算字符串以创建带有子图的图

python - 使用 matplotlib 在 Pandas groupby 上绘制直方图

python - 如何最有效地检测 Python 中目录的文件添加/删除/重命名更改?

python - 尝试使用多处理来填充 python 中的数组

c++ - 返回 const char*;静电有多难看?

python - pandas 在 to_latex 时用任意数字替换 NAN

python - 使用字典通过分配功能将一些列添加到数据框中

python - 通过 RESTful API 使用 python 与 MOXA ioLogik1214 进行连接,以将数据放入 DO 端口

python - 改变最大值#of python 脚本中允许的同步 Actor