这是因为您为现有系列分配了
a1data.loc[:, 'Total(%)']
,它保持了原始的dtype。相反,用新的系列覆盖:
a1data['Total(%)'] = convert_object_to_int(a1data['Total(%)'])
print(a1data.dtypes)
# Total(%) int64
# dtype: object
另请注意,您不需要重新分配函数中的所有中间体,您可以将其简化为:
def convert_object_to_int(column):
column = pd.to_numeric(column.astype(str)
.str.rstrip('%'),
errors='coerce')
return column.fillna(column.median()).astype(int)
或者没有任何变量:
def convert_object_to_int(column):
return (pd.to_numeric(column.astype(str)
.str.rstrip('%'),
errors='coerce')
.pipe(lambda x: x.fillna(x.median()))
.astype(int)
)