简体   繁体   中英

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. eg if the products asset class is stock indices or single stocks, then round the price in the trade price column by 2 dp. If its asset class is currencies then round it by 5 dp and if asset class is commodities round it by 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM