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

在下面的示例代码中,如何将Col1中的值舍入为2位小数.

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

推荐答案

您可以使用Col1round(num, 2)列上的panda.apply将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

Python相关问答推荐

Pandas 第二小值有条件

滚动和,句号来自Pandas列

如何标记Spacy中不包含特定符号的单词?

运行Python脚本时,用作命令行参数的SON文本

如何在polars(pythonapi)中解构嵌套 struct ?

Python—从np.array中 Select 复杂的列子集

Pandas计数符合某些条件的特定列的数量

在pandas中使用group_by,但有条件

移动条情节旁边的半小提琴情节在海运

try 检索blob名称列表时出现错误填充错误""

使用Python从rotowire中抓取MLB每日阵容

Python避免mypy在相互引用中从另一个类重定义类时失败

为什么Python内存中的列表大小与文档不匹配?

当单元测试失败时,是否有一个惯例会抛出许多类似的错误消息?

Beautifulsoup:遍历一个列表,从a到z,并解析数据,以便将其存储在pdf中.

如何过滤组s最大和最小行使用`transform`'

如何在GEKKO中使用复共轭物

在matplotlib中重叠极 map 以创建径向龙卷风图

时长超过24小时如何从Excel导入时长数据

FileNotFoundError:[WinError 2]系统找不到指定的文件:在os.listdir中查找扩展名