如何根据另一列中的整数舍入一列中的值

How do I round values in a column based on integers in another column

我需要在 Python 中将列中的价格四舍五入为不同的小数位数。我正在使用此代码创建数据框,df_prices:

    df_prices = pd.DataFrame({'InstrumentID':['001','002','003','004','005','006'], 'Price':[12.44,6.5673,23.999,56.88,4333.22,27.8901],'RequiredDecimals':[2,0,1,2,0,3]})

数据如下所示:

InstrumentID    Price      RequiredDecimals  
1              12.444     2  
2              6.5673     0  
3              23.999     1  
4              56.88      2  
5              4333.22    0  
6              27.8901    3  

我经常收到这个问题:

TypeError: cannot convert the series to

这些语句都不起作用:

    df_prices['PriceRnd'] = np.round(df_prices['Price'] , df_prices['RequiredDecimals'])

    df_prices['PriceRnd'] = df_prices['Price'].round(decimals = df_prices['RequiredDecimals'] )

最终输出应该是这样的:

Instrument#    Price      RequiredDecimals     PriceRnd  
1              12.444     2                    12.44  
2              6.5673     0                    7  
3              23.999     1                    24.0  
4              56.88      2                    56.88  
5              4333.22    0                    4333   
6              27.8901    3                    27.890

找不到更好的解决方案,但这个似乎可行

df['Rnd'] = [np.around(x,y) for x,y in zip(df['Price'],df['RequiredDecimals'])]

虽然不优雅,但你可以试试这个

import pandas as pd
df_prices = pd.DataFrame({'InstrumentID':['001','002','003','004','005','006'], 'Price':[12.44,6.5673,23.999,56.88,4333.22,27.8901],'RequiredDecimals':[2,0,1,2,0,3]})
print(df_prices)
list1 = []
for i in df_prices.values:
    list1.append('{:.{}f}' .format(i[1], i[2]))
print(list1)
df_prices["Rounded Price"] =list1
print(df_prices)

  InstrumentID      Price  RequiredDecimals Rounded Price
0          001    12.4400                 2         12.44
1          002     6.5673                 0             7
2          003    23.9990                 1          24.0
3          004    56.8800                 2         56.88
4          005  4333.2200                 0          4333
5          006    27.8901                 3        27.890

或1行代码

df_prices['Rnd'] = ['{:.{}f}' .format(x, y) for x,y inzip(df_prices['Price'],df_prices['RequiredDecimals'])]

另一种方法是用适当的系数调整您尝试四舍五入的数字,然后利用 .round() 函数始终四舍五入到最接近的整数这一事实。
df_prices['factor'] = 10**df_prices['RequiredDecimals'] df_prices['rounded'] = (df_prices['Price'] * df_prices['factor']).round() / df_prices['factor']
四舍五入后,数字再次除以因数。