这是我的代码。
import numpy as np
import pandas as pd
df = pd.read_csv('dataset2.csv')
x = []
y = []
# Populate x and y values from csv :
for z in df['x'][0:]:
x.append(float(z))
for z in df['y'][0:]:
y.append(float(z))
x_mean = float(np.array(x).mean())
y_mean = float(np.array(y).mean())
num = 0.0
den = 0.0
print("type of num",type(num))
for z in range(len(x)):
num += float(y[z]) - float(y_mean)
den += float(x[z]) - float(x_mean)
print("type of num",type(num))
print("Numerator is",num)
print("Denominator is",den)
在这一点上,我的整个代码都得到了Nan值。
Output :
type of num <class 'float'>
type of num <class 'float'>
Numerator is nan
Denominator is 1.8836487925000256e-11
Process finished with exit code 0
dataset2.csv文件。dataset2.csv
我试着在所有地方强制执行浮点类型转换,但没有用。
看起来你的数据集中有一个NaN值,df.info()的结果是。
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 700 entries, 0 to 699
Data columns (total 2 columns):
x 700 non-null float64
y 699 non-null float64
dtypes: float64(2)
memory usage: 11.0 KB
如果你可以用零代替NaNs,你可以添加这个。
y = np.nan_to_num(y)
在这一步之后,
for z in df['y'][0:]:
y.append(float(z))
我测试了你的代码后,得到的结果如下:
type of num <class 'float'>
type of num <class 'float'>
Numerator is -2.4726887204451486e-12
Denominator is 1.8836487925000256e-11
根据你的源代码:
num += float(y[z]) - float(y_mean)
num
依赖于两个变量,你应该把它们打印出来或者加一个检查。
if math.isnan(y[z]) or math.isnan(y_mean) :
# sound the alarm