【问题标题】:Selecting value in a pandas dataframe column, corresponding to values in other columns在 pandas 数据框列中选择值,对应于其他列中的值
【发布时间】:2018-11-23 17:39:12
【问题描述】:

所以我是 python 新手,我正在使用 pandas 的数据框(不能使用除了 pandas 的包),我已经为 6 种不同的汽车信息输入了用户输入(品牌、型号、类型、评级)汽车:

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

我想要这个数据的条件概率,我使用 value_counts 数据框来做到这一点,

print df.groupby('rating')['type'].value_counts()
print df.groupby('rating')['type'].count()
conditional = (df.groupby('rating')['type'].value_counts() / df.groupby('rating')['type'].count()).reset_index(name="Cond")
print conditional

这导致了我正在寻找的条件概率:

  rating   type  cond
0      A  coupe         0.500000
1      A  sedan         0.500000
2      B  sedan         0.666667
3      B  coupe         0.333333
4      C  sedan         1.000000

现在我需要打印单个概率。我将如何根据“制造”和“模型”列中的条件在这里选择个别概率?

例如在条件概率数据帧上,条件概率 P(type=sedan|rating=B) = 0.666667。我想选择并打印这个单独的概率,但是我不想根据索引(如“cond”列上的索引 2)打印,而是通过在 rating = B 时选择“cond”中的值并输入=轿车

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    IIUC 通过使用crosstabnormalize

    pd.crosstab(df.rating,df.type,normalize='index').stack().reset_index()
    Out[36]: 
      rating   type         0
    0      A  coupe  0.500000
    1      A  sedan  0.500000
    2      B  coupe  0.333333
    3      B  sedan  0.666667
    4      C  coupe  0.000000
    5      C  sedan  1.000000
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 1970-01-01
      • 2020-03-07
      • 1970-01-01
      相关资源
      最近更新 更多