Convert float to int and leave null

I have the following data framework, I want to convert the values ​​in column 'b' to integer

    a   b       c
0   1   NaN     3
1   5   7200.0  20
2   5   580.0   20

The following code throws an exception "ValueError: cannot convert NA to integer"

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

How to convert only float to int and leave zeros like?

+4
source share
1 answer

np.NaNis just a floating point, so it needs to be removed to create an integer pd.Series. Jeon's suggestion works fine if 0 is not a valid value in df['b']. For instance:

import pandas as pd
import numpy as np

df = pd.DataFrame({'a': [1, 5, 5], 'b': [np.NaN, 7200.0, 580.0], 'c': [3, 20, 20]})
print(df, '\n\n')

df['b'] = np.nan_to_num(df['b']).astype(int)

print(df)

0, (, -999999999), , 0.

, , 0, NaNs. , (, ..).

+2

Source: https://habr.com/ru/post/1655752/


All Articles