【问题标题】:Pandas: rounding halfway values in dataframe using np.round and applymap熊猫:使用 np.round 和 applymap 在数据框中舍入中途值
【发布时间】:2015-12-15 13:54:02
【问题描述】:

我想了解为什么在同一个 DF 上使用 1) np.round 和 2) applymap 时会得到不同的值

我的朋友

 df1 = pd.DataFrame({'total': [25.23, 3.55, 76.55, 36.48, 45.59]}, index=['cat1', 'cat2', 'cat3', 'cat4', 'cat5'])

      total
cat1  25.23
cat2   3.55
cat3  76.55
cat4  36.48
cat5  45.59

np.round 返回

np.round(df1, 1)
      total
cat1   25.2
cat2    3.6
cat3   76.6
cat4   36.5
cat5   45.6

appymap 返回

df1.applymap(lambda x: round(x,1))
      total
cat1   25.2
cat2    3.5
cat3   76.5
cat4   36.5
cat5   45.6

如您所见,np.round 向上取整中值,而 applymap 向下取整。怎么回事?

【问题讨论】:

标签: numpy pandas decimal rounding


【解决方案1】:

这是 python 2 中记录的行为:roundnp.around 在 python 3 中你会得到相同的结果:

In [63]:
np.round(df1['total'], 1)

Out[63]:
cat1    25.2
cat2     3.6
cat3    76.6
cat4    36.5
cat5    45.6
Name: total, dtype: float64

In [69]:
df1.applymap(lambda x: round(x,1))

Out[69]:
      total
cat1   25.2
cat2    3.6
cat3   76.6
cat4   36.5
cat5   45.6

【讨论】:

  • 吹毛求疵:Python 3 的 roundnp.around 在中途的情况下并不总是给出相同的结果:在 theory 中,np.around 确实是圆形的-甚至,但在实践中,它有一个不正确的实现,而不是有时会出现中途错误。 Python 的round 是正确舍入的,所以应该总是给出正确的结果(如果不是,这是一个可报告的错误)。例如,将np.around(0.025, 2)round(0.025, 2) 进行比较。 (两者都应该四舍五入,因为使用二进制浮点所见即所得,0.025 实际上是0.025000000000000001387778780781445675529539585113525390625。)
  • @MarkDickinson 这很有趣且有效,我觉得这是由于此处的 python 2 差异,但 OP 没有回应
猜你喜欢
  • 2017-05-09
  • 1970-01-01
  • 2020-04-13
  • 1970-01-01
  • 1970-01-01
  • 2019-02-11
  • 2018-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多