是否有任何理由为什么pandas在更新时将列的类型从int更改为float,我可以阻止它执行吗?以下是该问题的一些示例代码
import pandas as pd
import numpy as np
df = pd.DataFrame({'int': [1, 2], 'float': [np.nan, np.nan]})
print('Integer column:')
print(df['int'])
for _, df_sub in df.groupby('int'):
df_sub['float'] = float(df_sub['int'])
df.update(df_sub)
print('NO integer column:')
print(df['int'])
Run Code Online (Sandbox Code Playgroud)
原因如下:由于您有效地屏蔽了列上的某些值并替换它们(使用您的更新),因此某些值可能会变成 `nan
在整数数组中这是不可能的,因此数字 dtypes 先验转换为浮点数(为了效率),因为首先检查比这样做更昂贵
改变 dtype 是可能的......只是现在不在代码中,因此这是一个错误(虽然有点难以修复):github.com/pydata/pandas/issues/4094