python - 在 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”中的值并输入=轿车
解决方案
IIUC 通过使用crosstab
withnormalize
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
推荐阅读
- azure - Azure CosmosDb 中的动态属性/透视行为
- docker - 无法访问内部网络中 vm 上运行的容器 url
- c# - 如何更改将在任务栏上显示的图标
- java - 即使在 setText 之后芯片文本也是空的
- c# - 将行为添加到相互调用的重写重载
- apache-flink - 生成“心跳”类型的事件来推动事件时间
- r - 如何将 stat_poly_eq 标签放在构面图之外?
- python - ImportError:无法从“importlib”导入名称“元数据”
- gdb - 在 QNX gdb 上运行可执行文件而不重新上传它
- vue.js - Nuxt.js:如何从布局中引用页面数据?(例如,填充 og:title 标签)