程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

熊猫系列与整个DataFrame之间的关联

发布于2019-11-11 14:19     阅读(757)     评论(0)     点赞(22)     收藏(3)


我有一系列值,并且正在计算给定表的每一行的皮尔逊相关性。

我该怎么做?

例:

import pandas as pd

v = [-1, 5, 0, 0, 10, 0, -7]
v1 = [1, 0, 0, 0, 0, 0, 0]
v2 = [0, 1, 0, 0, 1, 0, 0]
v3 = [1, 1, 0, 0, 0, 0, 1]

s = pd.Series(v)
df = pd.DataFrame([v1, v2, v3], columns=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

# Here I expect ot do df.corrwith(s) - but won't work

使用Series.corr()来计算,预期产量

-0.1666666666666666  # correlation with the first row
0.83914639167827343  # correlation with the second row
-0.35355339059327379 # correlation with the third row

解决方案


你需要同样indexSeries作为columnsDataFrame对对齐SeriesDataFrame,并添加axis=1corrwith进行行的相关性:

s1 = pd.Series(s.values, index=df.columns)
print (s1)
a    -1
b     5
c     0
d     0
e    10
f     0
g    -7
dtype: int64

print (df.corrwith(s1, axis=1))
0   -0.166667
1    0.839146
2   -0.353553
dtype: float64

print (df.corrwith(pd.Series(v, index=df.columns), axis=1))
0   -0.166667
1    0.839146
2   -0.353553
dtype: float64

编辑:

您可以指定列并使用子集:

cols = ['a','b','e']

print (df[cols])
   a  b  e
0  1  0  0
1  0  1  1
2  1  1  0

print (df[cols].corrwith(pd.Series(v, index=df.columns), axis=1))
0   -0.891042
1    0.891042
2   -0.838628
dtype: float64


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/150188/b0036ee0a7e79f154154/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

22 0
收藏该文
已收藏

评论内容:(最多支持255个字符)