首页 > 解决方案 > 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 列来执行操作...

标签: pythonpandasstatisticsdata-sciencecorrelation

解决方案


这是你想要达到的目标:

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

推荐阅读