熊猫:如何用nan保持列的类型?

ros*_*fun 2 python dataframe pandas

例如,我有一个dfnan和使用下面的方法来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()
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

实际上,我希望column 1维持类型int而不是float.

我想要的输出:

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
Run Code Online (Sandbox Code Playgroud)

那怎么办呢?

cs9*_*s95 5

尝试添加downcast='infer'向下转发任何符合条件的列:

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

   0   1     2
0  2  10  4.20
1  b  70  0.03
2  x   0  0.00
Run Code Online (Sandbox Code Playgroud)

而相应的dtypes

0     object
1      int64
2    float64
dtype: object
Run Code Online (Sandbox Code Playgroud)