【问题标题】:get joint probability from pd dataframe从 pd 数据帧中获取联合概率
【发布时间】:2020-11-03 05:40:33
【问题描述】:

我有以下数据框

{'state': {7192: 'healthy',
  7193: 'healthy',
  7194: 'healthy',
  7195: 'Non healthy',
  7196: 'Non healthy'},
 'type': {7192: 'W', 7193: 'A', 7194: 'W', 7195: 'W', 7196: 'A'}}

我想知道与这个 df 相关的联合概率。

P(状态 = 健康,类型 = A),P(状态 = 健康,类型 = W) P(状态 = 不健康,类型 = A),P(状态 = 不健康,类型 = W)

我尝试了 groupby 方法,但没有成功。最有效的方法是什么。

编辑:为了澄清一点,我想计算每一对(状态,类型)的出现。在上面的例子中,这应该是 P(状态=健康,类型= A)= 1/5,P(状态=健康,类型= W)= 2/5 P(状态 = 不健康,类型 = A)= 1/5,P(状态 = 不健康,类型 = W)= 1/5

谢谢,

【问题讨论】:

  • 你能详细说明联合概率吗?你到底想做什么?
  • 您可以使用prob140 来做到这一点

标签: python pandas dataframe filtering probability


【解决方案1】:

似乎您可以使用DataFrame.value_counts(normalize=True) 来实现您想要的。请注意,DataFrame.value_countspandas >= 1.1.0 的新内容。如果您使用的是旧版本,则可以使用不同的方法获得相同的结果。

首先将您的字典转换为pd.DataFrame

df = pd.DataFrame(data)

熊猫版本>= 1.1.0

probs = df.value_counts(["state", "type"], normalize=True)

print(probs)
healthy      W       0.4
             A       0.2
Non healthy  W       0.2
             A       0.2

# Select individual probabilitiy:
healthy_a_prob = probs[("healthy", "A")]

print(healthy_a_prob)
0.2

如果您的 pandas 早于 1.1.0,请将上述示例中的第一行替换为:

probs = df.groupby("state")["type"].value_counts() / len(df)

# rest is the exact same

如果你想要一个交叉列表的概率表,我建议使用pd.crosstabnormalize=True

crosstab_ptable = pd.crosstab(df["state"], df["type"], normalize=True)

print(crosstab_ptable)
type           A    W
state
Non healthy  0.2  0.2
healthy      0.2  0.4

如果您也对边际概率感兴趣,可以使用margins 参数:

crosstab_ptable = pd.crosstab(df["state"], df["type"], margins=True, normalize=True)

print(crosstab_ptable)
type           A    W  All
state
Non healthy  0.2  0.2  0.4
healthy      0.2  0.4  0.6
All          0.4  0.6  1.0

【讨论】:

  • 非常感谢您拥有旧版熊猫!
  • 太棒了!如果这对您有用,您是否介意将此答案选为正确的,以便其他有相同/相似问题的用户可以快速找到解决方案?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-14
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 2016-10-03
  • 1970-01-01
  • 2022-01-10
相关资源
最近更新 更多