使用 python 根据另一列中的相应值舍入一列中的小数

Using python to round decimals in a column based on the corresponding value in another column

我正在尝试根据 Python 上的另一列(资产 class)对一列(价格)中的值进行四舍五入。例如,如果产品资产 class 是股票指数或个股,则将交易价格列中的价格四舍五入 2 dp。如果其资产 class 是货币,则将其舍入 5 dp,如果资产 class 是商品,则将其舍入 3dp。

对于以后的问题,最好提供一个你期望的例子

我会这样做:

In [1]: import pandas as pd

In [2]: round(5.123421, 3)
Out[2]: 5.123

In [3]: df = pd.DataFrame([["stock",2.123421], ["currencie", 5.213298]],columns=["asset", "price"])

In [4]: df
Out[4]:
       asset     price
0      stock  2.123421
1  currencie  5.213298

In [5]: asset_rounding = {"stock": 2, "currencie": 5}

In [6]: df['price'] = df.apply(lambda row: round(row['price'], asset_rounding[row['asset']]), axis=1)

In [7]: df
Out[7]:
       asset   price
0      stock  2.1200
1  currencie  5.2133

首先,您创建一个字典,将资产 class 与它应该四舍五入的位数相匹配,然后您将 round 方法应用于所有基于 price 的单元格关于他们 asset 个细胞的价值