python - 如何访问 Pandas DataFrame 中的标称值和不确定性?
问题描述
我将不确定性模块与 Pandas 一起使用。目前,我能够将具有不确定性的数据框一起输出到电子表格中。我的主要目标是在相邻列中写入具有不确定性的数据框。但是如何访问数据框中的标称值或不确定性。下面给出了 MWE。
当前输出
一个 | 乙 |
---|---|
63.2+/-0.9 | 75.4+/-0.9 |
41.94+/-0.05 | 53.12+/-0.21 |
4.1+/-0.4 | 89.51+/-0.32 |
28.2+/-0.5 | 10.6+/-0.6 |
25.8+/-0.9 | 39.03+/-0.08 |
27.26+/-0.09 | 44.61+/-0.35 |
25.04+/-0.13 | 37.7+/-0.6 |
2.4+/-0.5 | 50.0+/-0.8 |
0.92+/-0.21 | 3.1+/-0.5 |
57.69+/-0.34 | 21.8+/-0.8 |
期望的输出
一个 | +/- | 乙 | +/- |
---|---|---|---|
63.2 | 0.9 | 75.4 | 0.9 |
41.94 | 0.05 | 53.12 | 0.21 |
4.1 | 0.4 | 89.51 | 0.32 |
28.2 | 0.5 | 10.6 | 0.6 |
25.8 | 0.9 | 39.03 | 0.08 |
27.26 | 0.09 | 44.61 | 0.35 |
25.04 | 0.13 | 37.7 | 0.6 |
2.4 | 0.5 | 50 | 0.8 |
0.92 | 0.21 | 3.1 | 0.5 |
57.69 | 0.34 | 21.8 | 0.8 |
MWE
from uncertainties import unumpy
import pandas as pd
import numpy as np
A_n = 100 * np.random.rand(10)
A_s = np.random.rand(10)
B_n = 100 * np.random.rand(10)
B_s = np.random.rand(10)
AB = pd.DataFrame({'A':unumpy.uarray(A_n, A_s), 'B': unumpy.uarray(B_n, B_s)})
AB_writer = pd.ExcelWriter('A.xlsx', engine = 'xlsxwriter', options={'strings_to_numbers': True})
AB.to_excel(AB_writer, sheet_name = 'Data', index=False, na_rep='nan')
AB_writer.close()
更新
我忘了提到 AB 不是如 MWE 中所示创建的,而是 MWE 中未给出的先前计算的结果。为了 MWE,我创建了 AB。所以简而言之,我将无法访问 A 和 B 标称值和不确定值。
解决方案
您可以使用str.split()
将每一列拆分为一列主要值和一列不确定性,如下所示:
# add the column labels here if you have more columns to process
# e.g. `for col in AB[['A', 'B', 'C']]:` if you want to process columns `A`, `B` and `C`
for col in AB[['A', 'B']]:
AB[[col, f'{col}+/-']] = AB[col].str.split(r'\+/-', expand=True)
# sort the columns to put the related columns together
AB = AB.sort_index(axis=1)
不建议在同一个数据框中有 2 列相同的列标签。在这里,我们将+/-
列与它们各自的源列名称一起命名,以便区分它们。
在这里,我们还使用.sort_index()
对列名进行排序以使相关列彼此相邻。
结果:
print(AB)
A A+/- B B+/-
0 63.2 0.9 75.4 0.9
1 41.94 0.05 53.12 0.21
2 4.1 0.4 89.51 0.32
3 28.2 0.5 10.6 0.6
4 25.8 0.9 39.03 0.08
5 27.26 0.09 44.61 0.35
6 25.04 0.13 37.7 0.6
7 2.4 0.5 50.0 0.8
8 0.92 0.21 3.1 0.5
9 57.69 0.34 21.8 0.8
推荐阅读
- html - 为什么我的图像不在一个列中?我在这里做错了什么?
- pytorch - 如何从输入 ID 中获取填充掩码?
- javascript - 使用 setIntervalAsync 启动和重新启动异步函数返回 TypeError 无法将 undefined 或 null 转换为对象
- c - 由于分段错误,我的代码未显示输出
- mysql - 返回组合键MYSQL的一半的最大值
- php - 如何在php中以动态形式关联答案和问题?
- php - 包含父目录中的文件
- python - 不同维度的numpy数组连接错误
- node.js - 运行“npm start”时的 Saleor-Storefront 错误
- python - 如何使用 Python 查找字典中所有键的所有子项