[英]Using python to round decimals in a column based on the corresponding value in another column
i'm trying to round values in one column (price) based on another column(asset class) on Python.我正在尝试根据 Python 上的另一列(资产类别)对一列(价格)中的值进行舍入。 eg if the products asset class is stock indices or single stocks, then round the price in the trade price column by 2 dp.
例如,如果产品资产class是股票指数或个股,则将交易价格栏中的价格四舍五入2 dp。 If its asset class is currencies then round it by 5 dp and if asset class is commodities round it by 3dp.
如果其资产 class 是货币,则将其舍入 5 dp,如果资产 class 是商品,则将其舍入 3dp。
For future questions, its best to provide an example of what you expect对于未来的问题,最好提供一个您期望的示例
I would do it like this:我会这样做:
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
First you create a dict that matches between an asset class to how many digits it should round to, then you apply the round
method on all of the price
cells based on the value of their asset
cells首先,您创建一个字典,将资产 class 与它应该舍入的位数相匹配,然后根据
asset
单元格的值对所有price
单元格应用round
入方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.