Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas corr() returning NaN too often

I'm attempting to run what I think should be a simple correlation function on a dataframe but it is returning NaN in places where I don't believe it should.

Code:

# setup
import pandas as pd
import io

csv = io.StringIO(u'''
id  date    num
A   2018-08-01  99
A   2018-08-02  50
A   2018-08-03  100
A   2018-08-04  100
A   2018-08-05  100
B   2018-07-31  500
B   2018-08-01  100
B   2018-08-02  100
B   2018-08-03  0
B   2018-08-05  100
B   2018-08-06  500
B   2018-08-07  500
B   2018-08-08  100
C   2018-08-01  100
C   2018-08-02  50
C   2018-08-03  100
C   2018-08-06  300
''')

df = pd.read_csv(csv, sep = '\t')

# Format manipulation
df = df[df['num'] > 50]
df = df.pivot(index = 'date', columns = 'id', values = 'num')
df = pd.DataFrame(df.to_records())

# Main correlation calculations
print df.iloc[:, 1:].corr()

Subject DataFrame:

       A      B      C
0    NaN  500.0    NaN
1   99.0  100.0  100.0
2    NaN  100.0    NaN
3  100.0    NaN  100.0
4  100.0    NaN    NaN
5  100.0  100.0    NaN
6    NaN  500.0  300.0
7    NaN  500.0    NaN
8    NaN  100.0    NaN

corr() Result:

    A    B    C
A  1.0  NaN  NaN
B  NaN  1.0  1.0
C  NaN  1.0  1.0

According to the (limited) documentation on the function, it should exclude "NA/null values". Since there are overlapping values for each column, should the result not all be non-NaN?

There are good discussions here and here, but neither answered my question. I've tried the float64 idea discussed here, but that failed as well.

@hellpanderr's comment brought up a good point, I'm using 0.22.0

Bonus question - I'm no mathematician, but how is there a 1:1 correlation between B and C in this result?

like image 229
elPastor Avatar asked Sep 23 '18 13:09

elPastor


1 Answers

The result seems to be an artefact of the data you work with. As you write, NAs are ignored, so it basically boils down to:

df[['B', 'C']].dropna()

       B      C
1  100.0  100.0
6  500.0  300.0

So, there are only two values per column left for the calculation which should therefore lead to to correlation coefficients of 1:

df[['B', 'C']].dropna().corr()

     B    C
B  1.0  1.0
C  1.0  1.0

So, where do the NAs then come from for the remaining combinations?

df[['A', 'B']].dropna()

       A      B
1   99.0  100.0
5  100.0  100.0


df[['A', 'C']].dropna()

       A      C
1   99.0  100.0
3  100.0  100.0

So, also here you end up with only two values per column. The difference is that the columns B and C contain only one value (100) which gives a standard deviation of 0:

df[['A', 'C']].dropna().std()

A    0.707107
C    0.000000

When the correlation coefficient is calculated, you divide by the standard deviation, which leads to a NA.

like image 200
Cleb Avatar answered Oct 17 '22 23:10

Cleb