【问题标题】:How to calculate conditional probability of values in dataframe pandas-python?如何计算数据框 pandas-python 中值的条件概率?
【发布时间】:2016-10-15 13:02:09
【问题描述】:

我想计算评级列中评级的条件概率('A','B','C')。

    company     model    rating   type
0   ford       mustang     A      coupe
1   chevy      camaro      B      coupe
2   ford       fiesta      C      sedan
3   ford       focus       A      sedan
4   ford       taurus      B      sedan
5   toyota     camry       B      sedan

输出:

Prob(rating=A) = 0.333333 
Prob(rating=B) = 0.500000 
Prob(rating=C) = 0.166667 

Prob(type=coupe|rating=A) = 0.500000 
Prob(type=sedan|rating=A) = 0.500000 
Prob(type=coupe|rating=B) = 0.333333 
Prob(type=sedan|rating=B) = 0.666667 
Prob(type=coupe|rating=C) = 0.000000 
Prob(type=sedan|rating=C) = 1.000000 

任何帮助,谢谢..!!

【问题讨论】:

  • 好吧,就去做吧:)。 Prob(type=coupe|rating=A) = Prob(type=coupe and rating=A) / Prob(rating=A).
  • 使用 pd.crosstab 怎么样?

标签: python pandas dataframe probability


【解决方案1】:

你可以使用groupby:

In [2]: df = pd.DataFrame({'company': ['ford', 'chevy', 'ford', 'ford', 'ford', 'toyota'],
                     'model': ['mustang', 'camaro', 'fiesta', 'focus', 'taurus', 'camry'],
                     'rating': ['A', 'B', 'C', 'A', 'B', 'B'],
                     'type': ['coupe', 'coupe', 'sedan', 'sedan', 'sedan', 'sedan']})

In [3]: df.groupby('rating').count()['model'] / len(df)
Out[3]:
rating
A    0.333333
B    0.500000
C    0.166667
Name: model, dtype: float64

In [4]: (df.groupby(['rating', 'type']).count() / df.groupby('rating').count())['model']
Out[4]:
rating  type
A       coupe    0.500000
        sedan    0.500000
B       coupe    0.333333
        sedan    0.666667
C       sedan    1.000000
Name: model, dtype: float64

【讨论】:

    【解决方案2】:

    你可以使用.groupby()和内置的.div()

    rating_probs = df.groupby('rating').size().div(len(df))
    
    rating
    A    0.333333
    B    0.500000
    C    0.166667
    

    和条件概率:

    df.groupby(['type', 'rating']).size().div(len(df)).div(rating_probs, axis=0, level='rating')
    
    coupe  A         0.500000
           B         0.333333
    sedan  A         0.500000
           B         0.666667
           C         1.000000
    

    【讨论】:

    • 我认为level参数应该是0,而不是1。
    • 你试过了吗?当我将上面的工作版本更改为level=0 时,我得到了缺失值。 rating_probs 必须与 rating 级别对齐,即级别 1。您还可以将 level=1 更改为 `level='rating` 以更好地了解其工作原理。刚刚进行了相应的编辑。
    • 有趣。我用level=1 得到了结果,但这些结果是不正确的。将其更改为 level=0 给了我正确的条件概率值。
    • 只是澄清一下 - 你是说上面的结果是错误的,还是你使用上面的代码得到了不同的结果?
    • 上面的结果看起来是正确的。我的数据集中得到了不正确的结果,我使用 level=0 进行了更正。
    【解决方案3】:

    您需要添加reindex 以添加0 缺失对的值:

    mux = pd.MultiIndex.from_product([df['rating'].unique(), df['type'].unique()])
    s = (df.groupby(['rating', 'type']).count() / df.groupby('rating').count())['model']
    s = s.reindex(mux, fill_value=0)
    print (s)
    A  coupe    0.500000
       sedan    0.500000
    B  coupe    0.333333
       sedan    0.666667
    C  coupe    0.000000
       sedan    1.000000
    Name: model, dtype: float64
    

    还有另一个解决方案,谢谢Zero:

    s.unstack(fill_value=0).stack()
    

    【讨论】:

    • s.unstack(fill_value=0).stack() 应该可以吗?
    【解决方案4】:

    首先,转换成 pandas 数据框。通过这样做,您可以利用 pandas 的 groupby 方法。

    collection = {"company": ["ford", "chevy", "ford", "ford", "ford", "toyota"],
                  "model": ["mustang", "camaro", "fiesta", "focus", "taurus", "camry"],
                  "rating": ["A", "B", "C", "A", "B", "B"],
                  "type": ["coupe", "coupe", "sedan", "sedan", "sedan", "sedan"]}
    
    df = pd.DataFrame(collection)
    

    然后,根据事件分组(即评分)。

    df_s = df.groupby('rating')['type'].value_counts() / df.groupby('rating')['type'].count()
    df_f = df_s.reset_index(name='cpt')
    df_f.head()  # your conditional probability table
    

    【讨论】:

    • 我放了 90 行 - 得到 89 行。
    【解决方案5】:

    pd.crosstab(df.type, df.rating, margins=True, normalize="index")

       rating     A       B       C
       type                           
       coupe   0.500000  0.5  0.000000
       sedan   0.250000  0.5  0.250000
       All     0.333333  0.5  0.166667
    

    这里的 All 行给出了 A、B 和 C 的概率,现在是条件概率。

    pd.crosstab(df.type, df.rating, margins=True, normalize="columns")

     rating   A      B       C     All
     type                                
     coupe   0.5  0.333333  0.0  0.333333
     sedan   0.5  0.666667  1.0  0.666667
    

    您的条件概率在表中,例如,给定类型的条件概率是轿跑车,并且在轿跑车行和 A 列中的 A 评级为 0.5。 概率(type=coupe|rating=A) = 0.5

    【讨论】:

    • 这是一个非常干净简洁的方法!只需要了解交叉表功能的工作原理。非常有用。
    猜你喜欢
    • 2016-04-12
    • 1970-01-01
    • 2019-12-23
    • 2017-05-22
    • 2017-12-07
    • 2017-10-31
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多