舍入数据帧中的值并丢失小数点



我正在尝试将熊猫数据帧的值四舍五入到最接近的整数,以便我可以在可能读取/保存到csv之前以这种方式保存数据帧。我不确定为什么我无法匹配 .round(( 方法在熊猫网站上描述的结果。这是我的代码:

import pandas as pd
import numpy as np
x1 = np.random.randn(10)
df1 = pd.DataFrame({'x':x1})
df1
x
0   0.540351
1   0.205924
2   0.619970
3   0.636680
4   -1.415081
5   0.162028
6   -0.080224
7   -0.022692
8   -0.367687
9   -0.365140
df1.round(0)
x
0   1.0
1   0.0
2   1.0
3   1.0
4   -1.0
5   0.0
6   0.0
7   0.0
8   0.0
9   0.0

我想获得"1"和"0" - 这是我根据在线文档所期望的 - https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.round.html。 显示 .round(十进制(的第三个示例将"1"和"0"提供给 B 列,而不是 1.0 和 0.0。

参数为 0的pd.Series.round通过四舍五入到小数点后 0 来完成其工作。不承诺转换为整数 dtype。为确保发生这种情况,您应该在单独的步骤中应用转换:

import pandas as pd
import numpy as np
np.random.seed(0)
x1 = np.random.randn(10)
df1 = pd.DataFrame({'x':x1})
print(df1['x'].round(0).astype(int))
0    2
1    0
2    1
3    2
4    2
5   -1
6    1
7    0
8    0
9    0
Name: x, dtype: int32

您可以使用format

df.x.map("{:.0f}".format).astype(int)
Out[471]: 
0    1
1    0
2    1
3    1
4   -1
5    0
6    0
7    0
8    0
9    0
Name: x, dtype: int32

最新更新