首页 > 解决方案 > 在 pandas 数据框列中选择值,对应于其他列中的值

问题描述

所以我是 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”中的值并输入=轿车

标签: pythonpandasdataframe

解决方案


IIUC 通过使用crosstabwithnormalize

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

推荐阅读