ZeroDivisionError while trying to plot corelation matrix

Viewed 400

I am trying to plot the corelation matrix from pandas dataframe

import matplotlib.pyplot as plt
import pandas as pd

data = pd.read_csv('data_for_corelation.csv', delimiter=';')
df = pd.DataFrame(data,columns=['A','B'])
plt.matshow(df.corr())
plt.show()

But I am getting an error at this line:

plt.matshow(df.corr())

And error is:

/usr/local/lib/python3.6/dist-packages/matplotlib/figure.py in figaspect(arg)
   2759     if isarray:
   2760         nr, nc = arg.shape[:2]
-> 2761         arr_ratio = nr / nc
   2762     else:
   2763         arr_ratio = arg

ZeroDivisionError: division by zero

Sample data:

print(df.head(10))

       A           B
0  249,640704  1,019356
1  242,324502  0,647166
2  243,495232  0,644257
3  243,310156   0,81684
4  243,511297  1,050207
5  239,435233  1,340164
6  240,091439  1,836193
7   241,08975  1,540461
8  237,017175  1,244953
9  236,141326  1,210147

How should I fix it?

1 Answers

If I run this line of check-code on your sample data:

df.describe()

I get this:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 2 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   A       10 non-null     object
 1   B       10 non-null     object
dtypes: object(2)
memory usage: 144.0+ bytes

This tell me that pandas is reading your two columns as str, not as "numbers". This is due the use of the character ',' as decimal separator, instead of '.', as already suggested by JohanC.
You can solve this problem by fixing the data-read operation:

data = pd.read_csv('data.csv', delimiter=';', decimal=',')

If I check again the dataframe, after this fix, I get:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 2 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   A       10 non-null     float64
 1   B       10 non-null     float64
dtypes: float64(2)
memory usage: 224.0 bytes

As you can see, this time your columns are interpreted as "numbers" (float). Then you can perform the correlation matrix:

enter image description here

Related