Pandas:如何保持与楠列的类型?

2024-04-27 02:48:54 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我有一个带有nandf,并使用以下方法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

实际上,我希望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

那怎么做呢?你知道吗


Tags: 方法importpandasdfobjectastypecol
1条回答
网友
1楼 · 发布于 2024-04-27 02:48:54

尝试添加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

相关问题 更多 >