例如,我有一个带有 nan
的 df
并使用以下方法来 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()
输出:
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
实际上,我希望第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
那么该怎么做呢?
最佳答案
尝试添加 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
对应的dtypes
是
0 object
1 int64
2 float64
dtype: object
关于python - Pandas:如何用 nan 维护列的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50653953/