代码之家  ›  专栏  ›  技术社区  ›  DrWhat

如何在数据帧内舍入集合列中的值?

  •  1
  • DrWhat  · 技术社区  · 2 年前

    置信区间计算返回一组括号内的两个数字,我将其放入数据帧中。从这一点上,我需要向下舍入这些值,并将输出放入excel文件中。

    import pandas as pd
    import xlwings
    
    # example data frame
    inp = [{'Id': 0, 'Col1': (1.245987, 3.12345), 'Col2': 9},
           {'Id': 1, 'Col1': (1.3386, 3.19826), 'Col2': 9},
           {'Id': 2, 'Col1': (1.4673, 3.23462), 'Col2': 10},
           {'Id': 3, 'Col1': (1.562624, 3.32546), 'Col2': 10}, 
           {'Id': 4, 'Col1': (1.2573, 3.436537), 'Col2': 11},
           {'Id': 5, 'Col1': (1.273883, 3.58924), 'Col2': 12}
           ]
    df = pd.DataFrame(inp)
    
    
    # round down col1 values
    ### df["Col1"] = df["Col1"].round(2)    # doesn't work
    
    df["Col1"] = df["Col1"].astype(str)       # without this, values not exported by xlwings
    
    book = xlwings.Book(r'C:\Users\Dyer01\Documents\Mappe1.xlsx')
    sheet = book.sheets["Tabelle1"]
    sheet.range("c3").options(header=False, index=False).value = df
    

    我需要的是:

       Id      Col1        Col2
    0   0  (1.25, 3.12)     9
    1   1  (1.34, 3.20)     9
    2   2  (1.47, 3.23)    10
    3   3  (1.56, 3.33)    10
    4   4  (1.26, 3.44)    11
    5   5  (1.27, 3.60)    12
    
    1 回复  |  直到 2 年前
        1
  •  2
  •   I'mahdi    2 年前

    您可以使用 panda.apply 在列上 Col1 round(num, 2) 用于将NUM舍入到2位小数。

    df['Col1'] = df['Col1'].apply(lambda x : tuple([round(x[0], 2), round(x[1], 2)]))
    print(df)
    

       Id          Col1  Col2
    0   0  (1.25, 3.12)     9
    1   1   (1.34, 3.2)     9
    2   2  (1.47, 3.23)    10
    3   3  (1.56, 3.33)    10
    4   4  (1.26, 3.44)    11
    5   5  (1.27, 3.59)    12
    

    如果要在舍入后加零,可以使用 f-string

    >>> df['Col1'].apply(lambda x : f'({round(x[0], 2):.2f}, {round(x[1], 2):.2f})')
    
    0    (1.25, 3.12)
    1    (1.34, 3.20)
    2    (1.47, 3.23)
    3    (1.56, 3.33)
    4    (1.26, 3.44)
    5    (1.27, 3.59)
    Name: Col1, dtype: object
    
        2
  •  0
  •   Pythonic User    2 年前

    我们可以利用numpy np.round 函数来实现这一点,首先我们用某个小数点对其进行四舍五入,在本例中,我们将其设置为2,然后将其转换回元组。

    import numpy as np
    
    df['Col1'] = df['Col1'].apply(lambda r: np.round(r,decimals=2))
    df['Col1'] = tuple(map(tuple,df['Col1']))
    

        Id     Col1       Col2
    0   0   (1.25, 3.12)    9
    1   1   (1.34, 3.2)     9
    2   2   (1.47, 3.23)    10
    3   3   (1.56, 3.33)    10
    4   4   (1.26, 3.44)    11
    5   5   (1.27, 3.59)    12