00_*_*_00 11 python floating-point precision pandas
我有一个数据帧
df = pd.DataFrame(data=np.arange(10),columns=['v']).astype(float)
如何确保数字v是整数?我非常关心舍入/截断/浮点表示错误
cs9*_*s95 15
astype(int)暂时将您的列转换为int并测试np.array_equal:
np.array_equal(df.v, df.v.astype(int))
True
float.is_integer您可以将此python函数与以下内容结合使用apply:
df.v.apply(float.is_integer).all()
True
或者,all在生成器理解中使用python ,以提高空间效率:
all(x.is_integer() for x in df.v)
True
小智 12
这是一种更简单且可能更快的方法:
(df[col] % 1  == 0).all()
忽略空值:
(df[col].fillna(-9999) % 1  == 0).all()
如果要检查数据框中的多个浮点列,可以执行以下操作:
col_should_be_int = df.select_dtypes(include=['float']).applymap(float.is_integer).all()
float_to_int_cols = col_should_be_int[col_should_be_int].index
df.loc[:, float_to_int_cols] = df.loc[:, float_to_int_cols].astype(int)
请记住,包含所有整数的浮点列如果具有np.NaN值则不会被选中。要将具有缺失值的浮点列转换为整数,您需要填充/删除缺失值,例如,使用中值插补:
float_cols = df.select_dtypes(include=['float'])
float_cols = float_cols.fillna(float_cols.median().round()) # median imputation
col_should_be_int = float_cols.applymap(float.is_integer).all()
float_to_int_cols = col_should_be_int[col_should_be_int].index
df.loc[:, float_to_int_cols] = float_cols[float_to_int_cols].astype(int)
为了完整起见,Pandas v1.0+提供了convert_dtypes()实用程序,该实用程序(以及其他 3 个转换)对仅包含整数的所有数据帧列(或系列)执行请求的操作。
如果您想将转换限制为仅单个列,您可以执行以下操作:
>>> df.dtypes          # inspect previous dtypes
v                      float64
>>> df["v"] = df["v"].convert_dtype()
>>> df.dtypes          # inspect converted dtypes
v                      Int64
| 归档时间: | 
 | 
| 查看次数: | 10139 次 | 
| 最近记录: |