简体   繁体   中英

Why am i getting Nan value when trying to print this variable?

This is my Code:

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)

Further this point all throughout my code, I'm getting Nan values.

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 file: dataset2.csv

I've tried to enforce float type conversion literally everywhere, but to no avail.

According to your source code:

num += float(y[z]) - float(y_mean)

num depends on two variables, you should print them out or add a check:

if math.isnan(y[z]) or math.isnan(y_mean) :
    # sound the alarm

Looks like there is a NaN value in your dataset. df.info() yields:

<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

If it is ok for you to replace NaNs with zeroes, you can add this:

y = np.nan_to_num(y)

After this step:

for z in df['y'][0:]:
    y.append(float(z))

I tested you code after this change and I am getting the following output:

type of num <class 'float'>
type of num <class 'float'>
Numerator is -2.4726887204451486e-12
Denominator is 1.8836487925000256e-11

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM