Home > Software engineering >  pandas.errors.IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer
pandas.errors.IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer

Time:01-03

I am converting column in csv with prices to diferent value(currency change) with Pandas. I get this error an i suspect it is due to length of the column which is 35000 rows.

data = pd.read_csv(r"products.csv")
df = pd.DataFrame(data, columns=["Price"])
df["Price"] = df["Price"].astype(int)


def divide_by_7_5(numbers):
    return [number / 7.5 for number in numbers]


result = divide_by_7_5(df)
print(result)

Error----->. pandas.errors.IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer

I try to add:

low_memory=False

i didn't give positive result.

CodePudding user response:

I don't think your code is doing what you expect.

When looping over a dataframe, you loop over the column names:

df = pd.DataFrame({'col1': [0, np.nan, np.inf], 'col2': [1, 2, 3]})

def divide_by_7_5(numbers):
    for number in numbers:
        print(number)

divide_by_7_5(df)

Output:

col1
col2

If you just want to divide by 7.5, a simple numbers / 7.5 is sufficient, no need to handle NaN or Inf in a special way:

def divide_by_7_5(numbers):
    return numbers / 7.5

result = divide_by_7_5(df)

Output:

   col1      col2
0   0.0  0.133333
1   NaN  0.266667
2   inf  0.400000
  • Related