【发布时间】:2019-01-17 06:12:10
【问题描述】:
我从数据框中抓取了一行,如下所示:
https://i.stack.imgur.com/Y9LUE.png
或
Clicks Spend clk_ar CPC AdRank temp tempRan
36.0 248.76 59.94 6.91 1.67 1.665 1.67
我需要在 temp 列中用 2 位数字舍入值
选项 1:
round(df.temp,2)
OUTPUT:
1676725 1.66
Name: temp, dtype: float64
选项 2:
df.temp.apply(lambda x:round(x,2))
OUTPUT:
1676725 1.67
Name: temp, dtype: float64
两个轮函数表现出不同的行为。显然选项 1 与 python 3 行为一致。见Python 3.x rounding behavior
我只是想知道为什么选项 2 会这样。感谢您的帮助!
【问题讨论】:
-
另见here。
-
让我有点吃惊的是,使用 dtype
np.float64从 PandasSeries中提取值会得到实际的 Pythonfloat对象,而不是 NumPyfloat64对象。 (即使在 Python 的内置round函数下,这两个在 Python 3 上也有所不同。) -
除非您通过索引直接提取值,否则您确实会得到
np.float64实例而不是float实例。只有在apply下,您才能神秘地获得常规的floats。啊!
标签: python-3.x pandas dataframe lambda rounding