我正在使用不確定性模塊和 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 |
移動電源
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()
更新
I forgot to mention that AB is not created as shown in MWE, but is a result of previous calculations not given in the MWE. For the sake of MWE, I created the AB. So in short, I won't have access to the A and B nominal and uncertainty values.
uj5u.com熱心網友回復:
您可以映射列以獲得您正在尋找的結果。以下代碼映射A列(確保不要將兩列分配給同一個列鍵' /-')
AB[['A', ' /-']] = AB.A.apply(lambda x: str(x).split(' /-')).to_list()
uj5u.com熱心網友回復:
只需將它們分成不同的列:
Au = unumpy.uarray(A_n, A_s)
Bu = unumpy.uarray(B_n, B_s)
AB = pd.DataFrame({'A': unumpy.nominal_values(Au), 'A /-': unumpy.std_devs(Au), 'B': unumpy.nominal_values(Bu), 'B /-': unumpy.std_devs(Bu)})
uj5u.com熱心網友回復:
您可以使用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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/333965.html
