gpt4 book ai didi

python - 尝试绘制相关矩阵时出现 ZeroDivisionError

转载 作者:行者123 更新时间:2023-12-04 09:40:02 26 4
gpt4 key购买 nike

我正在尝试从 Pandas 数据框中绘制相关矩阵

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()

但我在这一行遇到错误:
plt.matshow(df.corr())

错误是:
/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

样本数据:
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

我该如何解决?

最佳答案

如果我在您的示例数据上运行这行检查代码:

df.describe()
我明白了:
<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
这告诉我 Pandas 正在将您的两列读为 str ,而不是“数字”。这是由于使用了字符 ','作为小数点分隔符,而不是 '.' ,正如 JohanC 已经建议的那样.
您可以通过修复数据读取操作来解决此问题:
data = pd.read_csv('data.csv', delimiter=';', decimal=',')
如果我再次检查数据框,在此修复后,我会得到:
<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
如您所见,这次您的列被解释为“数字”( float )。然后你可以执行相关矩阵:
enter image description here

关于python - 尝试绘制相关矩阵时出现 ZeroDivisionError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62374439/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com