一站式编码和相关

问题描述

我已经对列'postcode'进行了一次热编码,我希望看到该列与标记为:(mass customer = 0,affluent customer = 1 and high net worth customer = 2)的rich_segment之间的相关性。

我想看看邮政编码与客户财富之间是否存在关联。事情是,我有很多列邮政编码,因为我有一个热编码它。命名约定为postcode_XXXX(XXXX是4位数字)

我该怎么写才能仅找到这两个变量之间的相关性?我在数据框中还有100多个其他列,所以我不想简单地使用df.corr()方法

解决方法

如果只希望每个邮政编码列与财富细分列的相关值,则可以简单地遍历包含邮政编码的列名称,在每次迭代中过滤数据框,并在过滤的数据框上使用df.corr()。 / p>

例如:

cols = [c for c in df.columns if c.startswith('postcode_')]

for col in cols:
    filter_df = df[[col,'wealth_segment']]
    print(filter_df.corr())