David542
David542

Reputation: 110153

Proper way to convert to an int

What would be the proper way to do the following:

df['file_size'] = np.where(df['file_size'], int(df['file_size']), None)

Currently the error I get is:

TypeError: cannot convert the series to <class 'int'>

And when trying to do it directly:

df['file_size'] = df['file_size'].astype(int)

ValueError: Cannot convert non-finite values (NA or inf) to integer

Upvotes: 1

Views: 67

Answers (1)

jezrael
jezrael

Reputation: 862601

Use integer_na because by default at least one missing value convert integers to floats (because NaN is float), so need special type Int64 for resolve this problem:

df = pd.DataFrame({'file_size':[5,4,np.nan,None]})

df['file_size'] = df['file_size'].astype("Int64")
print (df)
   file_size
0          5
1          4
2       <NA>
3       <NA>

Upvotes: 2

Related Questions