Python 选择dataframe列中的值,对应于其他列中的值
因此,我是python新手,我正在使用pandas(除了pandas之外,我不能使用其他软件包)处理一个数据帧,并且我已经为6种不同的汽车的汽车信息获取了用户输入(品牌、型号、类型、等级):Python 选择dataframe列中的值,对应于其他列中的值,python,pandas,dataframe,Python,Pandas,Dataframe,因此,我是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 se
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
我想要这个数据的条件概率,我使用了一个值_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)打印,而是通过使用
交叉表和规范化IIUC为评级=B和类型=sedan时的“cond”中的值进行选择
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