0

I am writing a function to change from float to integer. Right now, for example, if the value is 1.34, the code returns 1.0 instead of 1. How to solve this problem?

dataframe.iloc[:,i] = dataframe.iloc[:,i].apply(lambda x: int(x) if str(x) != 'nan' else x)
Venkataraman R
  • 12,181
  • 2
  • 31
  • 58
Ye Htet
  • 27
  • 1
  • 6

1 Answers1

3

It's because NaN is a float:

>>> type(np.nan)
<class 'float'>
>>> 

Even 1 out of a million values is a float, than the whole thing is a float.

So you could use:

df.iloc[:, i] = df.iloc[:, i].astype('Int64')

You can do Int64, Int32 or Int16.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114