微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我的DataFrame表示每列中的属性,如果适用,则表示每行中的是/否值:

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

现在我需要计算每个属性组合的可能性,例如如果attribute1为yes,则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

到目前为止,我开始用整数(1/0)替换yes / no-values:

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中每列的总和,并将总和除以过滤行数(= 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)

是否有更简单,更优雅的方法来构造可能性数据框并为列和行标签保留相同的顺序?任何帮助将不胜感激!

解决方法:

一衬垫

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐