rosefun
rosefun

Reputation: 1857

Pandas: How to maintain the type of columns with nan?

For example,I have a df with nan and use the following method to fillna.

import pandas as pd 
a = [[2.0, 10, 4.2], ['b', 70, 0.03], ['x',  ]]
df = pd.DataFrame(a)
print(df)

df.fillna(int(0),inplace=True)
print('fillna df\n',df)
dtype_df = df.dtypes.reset_index()

OUTPUT:

   0     1     2
0  2  10.0  4.20
1  b  70.0  0.03
2  x   NaN   NaN
fillna df
    0     1     2
0  2  10.0  4.20
1  b  70.0  0.03
2  x   0.0  0.00
   col     type
0    0   object
1    1  float64
2    2  float64

Actually,I want the column 1 maintain the type of int instead of float.

My desired output:

fillna df
    0     1     2
0  2  10  4.20
1  b  70  0.03
2  x   0  0.00

   col     type
0    0   object
1    1  int64
2    2  float64

So how to do it?

Upvotes: 2

Views: 369

Answers (1)

cs95
cs95

Reputation: 402673

Try adding downcast='infer' to downcast any eligible columns:

df.fillna(0, downcast='infer')

   0   1     2
0  2  10  4.20
1  b  70  0.03
2  x   0  0.00

And the corresponding dtypes are

0     object
1      int64
2    float64
dtype: object

Upvotes: 5

Related Questions