作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图将 pandas 数据帧的一列中的值四舍五入到另一列中指定的小数位,如下面的代码所示。
df = pandas.DataFrame({
'price': [14.5732, 145.731, 145.722, 145.021],
'decimal': [4, 3, 2, 2]
})
df['price'] = df.apply(lambda x: round(x.price, x.decimal), axis=1)
但是,这样做会导致以下错误:
> df['price'] = df.apply(lambda x: round(x.price, x.decimal), axis=1)
E TypeError: ('integer argument expected, got float', 'occurred at index 0')
文档看起来似乎 round 期望在索引 0 处有一个浮点,但它显然不高兴。将价格更改为 int 可以修复错误,但这会破坏代码本身的意义。
最佳答案
这一直是 pandas 的痛点 loooong time 。当访问单行或沿第一个轴调用 apply 时,数据类型强制会相当定期地发生。该错误消息令人困惑,因为很明显,十进制系列的 dtype 是整数类型,因此它应该被 round
方法接受,但强制转换是在幕后发生的。
您可以使用iloc
和apply
来检查:
>>> df.iloc[0]
price 14.5732
decimal 4.0000
Name: 0, dtype: float64
>>> df.apply(lambda x: x, axis=1)
price decimal
0 14.5732 4.0
1 145.7310 3.0
2 145.7220 2.0
3 145.0210 2.0
更令人沮丧的是,如果您有一个对象 dtype 列,则不会强制执行任何操作,因此行为并不那么容易预测!
>>> df['foo'] = 'bar'
>>> df.iloc[0]
price 14.5732
decimal 4
foo bar
Name: 0, dtype: object
<小时/>
长话短说,这很令人困惑,而且一点也不直观。有几个解决方法是在 lambda 函数中转换小数或使用列表理解(可能比 apply 更快)。
>>> df.apply(lambda x: round(x.price, int(x.decimal)), axis=1)
0 14.5732
1 145.7310
2 145.7200
3 145.0200
dtype: float64
>>> [round(x, y) for x, y in zip(df['price'], df['decimal'])]
[14.5732, 145.731, 145.72, 145.02]
请注意,以系列显示时,表示形式不会改变,但值将被四舍五入。
关于python - 如何对两个 pandas 列进行舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59902217/
我是一名优秀的程序员,十分优秀!