gpt4 book ai didi

python - pandas.DataFrame 列中值组合的可能性

转载 作者:太空宇宙 更新时间:2023-11-03 10:50:11 24 4
gpt4 key购买 nike

我的 DataFrame 表示每列中的属性和每行中的yes/no值(如果适用):

d_att = { 'attribute1': ['yes', 'yes', 'no'],
'attribute2': ['no', 'yes', 'no'],
'attribute3': ['no', 'no', 'yes'] }

df_att = pd.DataFrame(data=d_att)
df_att

attribute1 attribute2 attribute3
0 yes no no
1 yes yes no
2 no no yes

现在我需要计算每个属性组合的可能性,例如如果 attribute1yes,则 attribute2 也为 yes 的可能性为 0.5。

我的目标是像这样的 DataFrame:

             attribute1  attribute2  attribute3
attribute1 1.0 0.5 0.0
attribute2 1.0 1.0 0.0
attribute3 0.0 0.0 1.0

到目前为止,我首先将 yes/no 值替换为整数 (1/0) :

df_att_int = df_att.replace({'no': 0, 'yes': 1})
df_att_int

attribute1 attribute2 attribute3
0 1 0 0
1 1 1 0
2 0 0 1

然后我定义了一个方法,它遍历每一列,过滤当前列中值为1的行的DataFrame,计算过滤后的DataFrame中每一列的总和,并将总和( s) 按当前列的筛选行数 (=sum):

def combination_likelihood(df):
df_dict = {}

for column in df.columns:
col_sum = df[df[column]==1].sum()
divisor = col_sum[column]
df_dict[column] = col_sum.apply(lambda x: x/divisor)

return pd.DataFrame(data=df_dict).T

在我的 df_att_int-DataFrame 上应用该方法可提供预期的结果:

df_att_comb_like = combination_likelihood(df_att_int)
df_att_comb_like

attribute1 attribute2 attribute3
attribute1 1.0 0.5 0.0
attribute2 1.0 1.0 0.0
attribute3 0.0 0.0 1.0

但是,如果属性/列名不是按字母顺序排列的,行将按标签排序,并且将丢失有洞察力的图所需的特征模式,例如导致以下结构:

             attribute2  attribute3  attribute1
attribute1 0.5 0.0 1.0
attribute2 1.0 0.0 1.0
attribute3 0.0 1.0 0.0

最终,我想将结果绘制成热图:

import seaborn as sns
sns.heatmap(df_att_comb_like)

seaborn heatmap

有没有一种更简单、更优雅的方法来构建似然数据框并保持列和行标签的相同顺序?任何帮助将不胜感激!

最佳答案

一行

虽然我把一些更好的东西放在一起

df_att.eq('yes').astype(int) \
.pipe(lambda d: d.T.dot(d)) \
.pipe(lambda d: d.div(d.max(1), 0))

attribute1 attribute2 attribute3
attribute1 1.0 0.5 0.0
attribute2 1.0 1.0 0.0
attribute3 0.0 0.0 1.0

更长

使数据帧成为整数掩码

d = df_att.eq('yes').astype(int)
d

attribute1 attribute2 attribute3
0 1 0 0
1 1 1 0
2 0 0 1

与自身的点积

d2 = d.T.dot(d)
d2

attribute1 attribute2 attribute3
attribute1 2 1 0
attribute2 1 1 0
attribute3 0 0 1

将每一行除以该行的最大值

d2.div(d2.max(axis=1), axis=0)

attribute1 attribute2 attribute3
attribute1 1.0 0.5 0.0
attribute2 1.0 1.0 0.0
attribute3 0.0 0.0 1.0

关于python - pandas.DataFrame 列中值组合的可能性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52117162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com