请查看代码和输出。
我可以知道为什么 *_state 列中的数据类型是 float 而不是 int 以及如何将这些数据类型转换为 int 吗?
谢谢,
代码
print(df_test)
for idx, row in df_test.iterrows():
print(type(row['value']))
df_test.at[idx, row['name'] + '_state'] = row['value']
print(df_test)
输出
Message name value
0 Door_Started Door 1
1 Light_open Light 1
type 'int'
type 'int'
Message name value Door_state Light_state
0 Door_Started Door 1 1.0 NaN
1 Light_open Light 1 NaN 1.0
请您参考如下方法:
您只是将一个整数分配给单个列 row['name'] + '_state'。对于任何给定的索引,这会导致 NaN 值出现在其他列中。
NaN 被认为是 float ( see here why ),因此 int 和 NaN 值的混合将对于任何给定系列,始终向上转换为 float1。您可以自己检查一下:
type(np.nan) # float
这通常不会中断后续的操作/计算,并且可以有效地保持您的系列 float 。将此类系列转换为 int 是不可能的,并且变通方法效率低下。因此,我建议您什么都不做。
1 docs 中描述了这种调节行为:
Note: When working with heterogeneous data, the dtype of the resulting ndarray will be chosen to accommodate all of the data involved. For example, if strings are involved, the result will be of object dtype. If there are only floats and integers, the resulting array will be of float dtype.
