python - Pandas Correlation - 在两列上处理 0
问题描述
情况:我正在使用一个大型数据框,大约 100 列和大约 200 万行。目标是找到每列之间的相关性。但是数据集的每一行都有很多 0 值,所以当我使用 时df.corr()
,结果不正确,因为两行之间的相关性,让我们假设 A 和 B,有很多(0, 0)
是不同的形式(x, y)
,对于x != 0 | y != 0
.
像这样:
#dataframe without zeros for both columns
df = pd.Dataframe([(.2, .3), (.1, .2), (.3, .6), (.6, .9),
(.5, .0), (.0, .5)], columns = ['dogs', 'cats'])
ρ = corr(dogs,cats) = 0.2482
#dataframe with lots of zeros for both columns
df = pd.Dataframe([(.2, .3), (.1, .2), (.3, .6), (.6, .9),
(.5, .0), (.0, .5), (.0, .0), (.0, .0), (.0, .0), (.0, .0)],
columns = ['dogs', 'cats'])
ρ = corr(dogs,cats) = 0.5743
#dataframe with np.NaN instead of every zero
df = pd.Dataframe([(.2, .3), (.1, .2), (.3, .6), (.6, .9),
(.5, .0), (.0, .5), (.0, .0), (.0, .0), (.0, .0), (.0, .0)],
columns = ['dogs', 'cats'])
df = df.replace(0, np.NaN)
ρ = corr(dogs,cats) = 0.9759
主要问题:在计算熊猫 df 中的相关性时使用 NaN 意味着它将忽略所有至少有一个零的集合,因此 df 变为:[(.2, .3), (.1, .2), (.3, .6), (.6, .9)]
。我需要在没有 (0, 0) 的情况下计算相关性,但是使用(0,y) & (x, 0)
, 目前我能想到的唯一可能的方法是构建两个 for 循环并遍历每一列......
像这样:
results = []
for (col_name_1, col_data_1) in df.iteritems():
for (col_name_2, col_data_2) in df.iteritems():
res = pd.concat([col_data_1, col_data_2])
#only get the rows that aren't (0,0)
res = res[!((res[col_name_1] == 0) & (res[col_name_2] == 0))]
#get the value from the correlation and save it
corr = result.corr().stack()[1]
results.append((col_name_1, col_data_2, corr,))
编辑 为了清楚起见,现在当我使用没有 for 循环的 df.corr() 时,需要 1 分钟。使用上面介绍的 for 循环,该过程在 30 多分钟前开始并且仍在运行。也许我应该更改为每个 df 列的 numpy 列来执行操作...
解决方案
这是你想要达到的目标:
df[~((df.dogs==0.0)&(df.cats==0.0))].corr()
dogs cats
dogs 1.000000 0.248199
cats 0.248199 1.000000
或者如果你愿意
rho = df[~((df.dogs==0.0)&(df.cats==0.0))].corr().iloc[1,0]
rho
0.24819888822736433
推荐阅读
- python - 带有 * 的 Python zip 行为
- node.js - Webpack - 捆绑所有节点模块,除了一个角度通用的
- php - 无法使用 Ajax 将 JS 值传递给 PHP
- php - cURL 请求耗时太长,代码有问题?
- java - 如何在 Git for Eclipse 中组织分层、模块化的 Java 项目?
- c# - moq.verify - 使用继承类型时使用基类型测试的泛型方法
- matlab - VideoReader/在matlab中读取
- bash - 我可以找到忽略大小写、破折号、空格或其他字符的类似命名文件吗?
- pg-promise - {pg-promise} postgres - 如何将 int[] 类型转换为与 POINT() 兼容
- python - 比较三个(或更多)字典并在至少两个相等时找到匹配项