【问题标题】:Using python to round decimals in a column based on the corresponding value in another column使用python根据另一列中的相应值对一列中的小数进行四舍五入
【发布时间】:2021-05-26 10:53:26
【问题描述】:

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

【问题讨论】:

    标签: python pandas dataframe multiple-columns rounding


    【解决方案1】:

    对于未来的问题,最好提供一个您期望的示例

    我会这样做:

    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
    

    首先,您创建一个匹配资产类别与其应四舍五入的位数之间的字典,然后根据 asset 单元格的值对所有 price 单元格应用 round 方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多