【问题标题】:how to compute correlation coefficient for multi-variable 1 column如何计算多变量1列的相关系数
【发布时间】:2018-12-13 04:29:08
【问题描述】:
Category  SubCategory  Month  Value
A         A1           Jan     1
A         A1           Feb     2
A         A1           Mar     3
A         A2           Jan     2
A         A2           Feb     3
A         A2           Mar     5
B         B1           Jan     1
B         B1           Feb     6
B         B1           Mar     7
B         B2           Jan     3
B         B2           Feb     6
B         B2           Mar     7

我有一个这样的示例 pandas df。我想计算子组类别 A1 和 A2、B1 和 B2 之间的相关系数,而不是 A1 和 B1 等。我的最终目标是有一个这样的表:

    A1        A2        B1     B2
A1  1.0000  0.9820      
A2  0.9820  1.0000      
B1                    1.0000    0.9963
B2                    0.9963    1.0000

谁能帮我写python代码?

显然,这个给了我每个 SubCategory 的 corr 值 1

df.groupby('SubCategory').corr()

【问题讨论】:

  • OP的数据没有被规范化,所以有可能不一致。因此,解决方案将依赖于数据有效这一事实,例如,如果将“Feb”中的一个替换为“Apr”,则 W-B 的解决方案将中断,而 indominus 的解决方案将中断 会在不检测错误的情况下给出结果(也是潜在的危险)

标签: python pandas correlation


【解决方案1】:

第一个是pivot 问题,然后只使用 corr

pd.concat([x.pivot('Month','SubCategory','Value').corr() for _,x in df.groupby('Category')])
                   A1        A2        B1        B2
SubCategory                                        
A1           1.000000  0.981981       NaN       NaN
A2           0.981981  1.000000       NaN       NaN
B1                NaN       NaN  1.000000  0.996271
B2                NaN       NaN  0.996271  1.000000

【讨论】:

  • 我可以知道为什么月份是索引吗?和 x[month].values 不显示在索引中
  • 感谢您的回答,它可以工作,但是对于实时应用程序,我有 4700x 4700 矩阵,其中大部分为空/NAN 值。有没有办法对这些进行分组(按类别创建新的 dfs?)
  • 跳过最后的pd.concat,您将获得 2 个单独的数据帧,每个类别一个。
  • @rookiescientist 只是不要做 concat
【解决方案2】:

数据

import pandas as pd
df = pd.DataFrame({"Category" :   ["A", "A", "A", "A", "A", "A", 
                                   "B", "B", "B", "B", "B", "B"], 
                   "SubCategory": ["A1", "A1", "A1", "A2", "A2", "A2", 
                                   "B1", "B1", "B1", "B2", "B2", "B2"],
                   "Value":       [1, 2, 3, 2, 3, 5, 
                                   1, 6, 7, 3, 6, 7]})

解决方案

import scipy as sp
# this will contain a list of DataFrames storing the correlation matrices
correlations = []
for g in df.groupby("Category"):
    sub_df = g[1][["SubCategory", "Value"]]
    data = sub_df.pivot_table(columns="SubCategory", values="Value", aggfunc=list)
    correlation = pd.DataFrame(sp.corrcoef(data.values.tolist()[0]), 
                               columns=data.columns.values.tolist(), 
                               index=data.columns.values.tolist())
    correlations.append(correlation)
pd.concat(correlations, sort=False)

输出

    A1          A2          B1          B2
________________________________________________
A1  1.000000    0.996271    NaN         NaN
A2  0.996271    1.000000    NaN         NaN
B1  NaN         NaN         1.000000    0.996271
B2  NaN         NaN         0.996271    1.000000

更新

这个方案在python和pandas版本上测试过如下图,旧版本可能不行:

from platform import python_version
print('python version:', python_version())
import pandas as pd
print('pandas version:', pd.__version__)

    python version: 3.7.0
    pandas version: 0.23.4

【讨论】:

  • 我复制粘贴了你的两个代码,它给了我这个错误: ValueError: Shape of passed values is (2, 2), indices imply (2, 1)
  • 在这一行:data = sub_df.pivot_table(columns="SubCategory", values="Value", aggfunc=list)
  • 嗯,我刚刚在手机上遇到了同样的错误,但我发誓我昨天在台式机上测试过,它工作正常。唯一的区别可能是我的桌面有 python 3.7,而我的手机有 3.6,可能还有不同版本的 pandad。我下午回家看看
  • 我刚刚重新启动了我的桌面并重新尝试了代码,它仍然有效。我怀疑这是软件包的版本。请问python和pandas是什么版本的?我的是 3.7.0 和 0.23.4。我刚刚在 github 上做了一个快速检查,似乎 pivot_table 是在 pandas 0.20 中添加的。
猜你喜欢
  • 1970-01-01
  • 2018-09-10
  • 2020-08-18
  • 1970-01-01
  • 2015-04-16
  • 2019-11-13
  • 2019-07-04
  • 1970-01-01
  • 2014-04-16
相关资源
最近更新 更多