使用Pandas将一列中的数字与另一列中显示的小数位数进行四舍五入

2024-05-19 19:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用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有效,但不是第一个


Tags: 代码importdataframepandasdfdataas数字
3条回答

因为你的问题更多的是关于理解两种不同的行为,所以我将把重点放在这一点上

代码#1

df['newcolA'] = round(df['numbers'] , df['decimal'])

df[“数字”]&;df['decimal']的类型为Series。实际上,您正在向round传递一个序列,但它需要一个数字。因此出现错误:TypeError:无法将序列转换为<;“int”类>

代码#2

df['numbers']*df['decimal']

Pandas允许使用矢量化操作在相同长度的两个系列之间执行各种操作

解决方案 有多种可能的解决方案,最惯用的方法是使用apply(已由@corrarien发布)

尝试:

>>> df.apply(lambda x: round(x['numbers'], int(x['decimal'])), axis=1)
0    1.230
1    2.346
2    3.460
dtype: float64

我已经调整了@correlian的解决方案,以避免引入任何多余的0(这些数字都是大于1的非整数实数,因此我相信我的noZero函数是正确的

import pandas as pd
from math import log10, floor

def noZero(x, rd):               # rd digits at right
   ld = floor(log10(x))+1        # ld digits at left
   x = round(x,rd)
   fmt = "{:<0"  + str(ld + 1 + rd) + "." +  str(rd) + "f}"
   x_str = fmt.format(x)
   return x_str

df = pd.DataFrame(
   data = {
      'numbers' : [1.2345, 2.3456, 3.4567, 3.399],
      'decimal' : [2, 3, 2, 2]
   }
)

df['newcolA'] = df.apply(lambda x: round(x['numbers'], int(x['decimal'])), axis=1)
df['happy :)'] = df.apply(lambda x: noZero(x['newcolA'], int(x['decimal'])), axis=1)
df

   numbers   decimal   newcolA   happy :)
0   1.2345      2       1.230    1.23
1   2.3456      3       2.346    2.346
2   3.4567      2       3.460    3.46
3   3.3990      2       3.400    3.40

相关问题 更多 >