【问题标题】:How to consider precision in another column while applying round(precision) to the value column in Dataframe, Python 3.6如何在对 Dataframe 中的值列应用 round(precision) 时考虑另一列的精度,Python 3.6
【发布时间】:2020-08-20 14:49:33
【问题描述】:

我有带列的 DataFrame:精度和值;精度包含整数值,如 1、2、3 小数位以传递轮函数。如何在对每个值执行舍入时传递“精度”字段?对于每个值,我必须根据字段“精度”应用舍入。

df = pd.DataFrame([[15.5666, 2], [14.32, 1], [14.68954, 3], [16.78, 1]], columns=['value', 'precision'])

df['value2'] = df['value'].round(df['precision'])

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    有时候for循环也不错

    [round(x, y) for x , y in zip(df['value'], df['precision'])]
    Out[128]: [15.57, 14.3, 14.69, 16.8]
    #df['value2'] = [round(x, y) for x , y in zip(df['value'], df['precision'])]
    

    【讨论】:

    • 我们可以在十进制值的末尾去掉零吗?比如 round(14.32000, 1) - 给出 14.30,我们可以只保留 14.3 吗?
    • @SPy 将其转换为 str 怎么样?,如果是数字,pandas 对象将使所有列格式相同
    猜你喜欢
    • 2021-02-09
    • 2019-04-18
    • 2021-10-28
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    相关资源
    最近更新 更多