我想使用Pandas将一列中的数字从另一列中显示的小数位数(不尽相同)取整
我的数据
numbers decimal
1.2345 2
2.3456 3
3.4567 2
预期输出:
numbers decimal newcolA
0 1.2345 2 1.23
1 2.3456 3 2.346
2 3.4567 2 3.46
我的代码#1
import pandas as pd
df = pd.DataFrame(
data = {
'numbers' : [1.2345, 2.3456, 3.4567],
'decimal' : [2,3,2]
}
)
df['newcolA'] = round(df['numbers'] , df['decimal'])
我得到以下错误: TypeError:无法将序列转换为<;“int”类>
但是,下面的类似的代码可以工作
我的代码#2
import pandas as pd
df = pd.DataFrame(
data = {
'numbers' : [1.2345, 2.3456, 3.4567],
'decimal' : [2,3,2]
}
)
df['newcolB'] = df['numbers']*df['decimal'] #The only difference
df
numbers decimal newcolB
0 1.2345 2 2.4690
1 2.3456 3 7.0368
2 3.4567 2 6.9134
我不明白什么?为什么代码2有效,但不是第一个
因为你的问题更多的是关于理解两种不同的行为,所以我将把重点放在这一点上
代码#1
df[“数字”]&;df['decimal']的类型为
Series
。实际上,您正在向round
传递一个序列,但它需要一个数字。因此出现错误:TypeError:无法将序列转换为<;“int”类>代码#2
Pandas允许使用矢量化操作在相同长度的两个系列之间执行各种操作
解决方案 有多种可能的解决方案,最惯用的方法是使用
apply
(已由@corrarien发布)尝试:
我已经调整了@correlian的解决方案,以避免引入任何多余的0(这些数字都是大于1的非整数实数,因此我相信我的noZero函数是正确的)
相关问题 更多 >
编程相关推荐