简体   繁体   English

使用 python 根据另一列中的相应值对列中的小数进行四舍五入

[英]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.

相关问题 列中的条件格式单元格基于它在另一列中的对应值 - Conditional format cell in column based on it corresponding value in another column dataframe 列如何与另一列的小数位数相同 - How round dataframe column with the same decimals quantity of another column 基于 pyspark 中的列值的舍入 - round based on column value in pyspark Python-基于另一个列值访问列 - Python - Access column based on another column value 根据python中的另一列映射列值 - Mapping column value based on another column in python 根据 Python 中的另一列更新列的值 - Updating the value of a column based on another column in Python pandas:根据另一列中的值获取具有相应索引的精确对应值 - pandas: get the exact corresponding value with the corresponding index based on a value in another column 需要在另一个文件中查找行模式并使用 python 获取特定列中相应值的总和 - Needs to find line pattern in another file and get the sum of corresponding value in particular column using python 使用Python熊猫根据条件将行值复制到另一列 - Copy a row value to another column based on condition using Python pandas Python用于具有相应列的矩阵值的列的矩阵 - Python for matrix of a column with matrix value by a corresponding column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM