我有一个数据文件df:
A B C
0 0 1 0
1 0 1 1
2 0 1 1
3 1 0 1
4 0 0 0
5 1 0 0
6 0 0 0
7 0 0 1
8 1 0 0
9 0 0 0
10 1 0 1
11 1 0 1
12 0 1 1
13 1 0 0
14 1 0 0
15 0 1 0
16 1 1 0
17 0 0 1
18 1 0 1
19 1 0 0
20 1 0 1
21 1 1 0
22 1 1 1
23 1 1 1
24 1 0 0
25 1 1 0
26 0 0 1
27 0 1 1
28 0 1 0
29 1 1 0
30 1 0 1
31 0 1 0
32 0 0 1
33 1 1 1
34 0 1 0
35 1 1 0
36 0 1 0
37 0 0 1
38 0 1 1
39 0 1 1我得到了联合概率P(A,B,C)
grp = df.apply(tuple, axis=1)
PrD=pd.concat([df.groupby(grp).first(),
grp.groupby(grp).count().div(len(df)).rename("Probs")],
axis=1).reset_index(drop=True)
print (PrD)输出联合概率P(A,B,C)
A B C Probs
0 0 0 0 0.075
1 0 0 1 0.125
2 0 1 0 0.150
3 0 1 1 0.150
4 1 0 0 0.150
5 1 0 1 0.150
6 1 1 0 0.125
7 1 1 1 0.075我试图编写一个函数,它接收PrD列名的子集,并计算符合规则P(A,B) =P(A,B)/P(B)的条件概率,如果它接收到3个变量:P(A,B,C)=P(A,B,C)/P(B,C),如果它接收到4个变量:P(A,B,C,D) =P(A,B,C,D)/P(B,C,D)等等。例如,如果函数接收到P(A=0|B=0),输出应该由(0.075+0.125)/(0.075+0.125+0.150+0.150) = 0.2计算,其中分子在A和B=0时,分母在B=0时,如果它接收到一个变量A=0,则返回(0.075+0.125+0.150+0.150 ),其中只有行,其中A=0尝试了loc and query,但是它们只接收一个变量,而不是多个变量。
发布于 2022-03-31 02:22:22
你是在电脑上做数学,这意味着应该做一些不同的事情。
你不需要建立联合概率表之类的。您可以计算A = 0和A and B = 0所在的行数,并将两者除以:
def prob(df, a, *cols):
"""Return the probability that all columns in `cols` are 0 given column `a` is 0
"""
if len(cols) == 0:
return df[a].eq(0).sum() / len(df)
else:
return df[[a] + list(cols)].eq(0).all(axis=1).sum() / df[list(cols)].eq(0).sum()用法:
prob(df, "A", "B") # 0.4
prob(df, "A", "B", "C") # 0.15https://stackoverflow.com/questions/71685819
复制相似问题