簡體   English   中英

如何使用來自定性信息的聚合數據完全重組表格

[英]How to completely reorganise a table using aggregate data from qualitative information

我有一個具有以下布局的熊貓數據框:

柱子 數據類型
'水粘合劑' 漂浮
'飛灰' 漂浮
'年齡' 整數
'力量 %' 漂浮

數據集樣本

年齡列是定性的,具有 1、3、7、14 和 28 天的記錄。 我想按水粘合劑和粉煤灰對行進行分組,計算每個年齡組的平均強度百分比,得到一個看起來像這樣的表格:

柱子 數據類型
'水粘合劑' 漂浮
'飛灰' 漂浮
'平均強度 % 1 天' 漂浮
'平均強度 % 3 天' 漂浮
'平均強度 % 7 天' 漂浮
'平均強度 % 14 天' 漂浮
'平均強度 % 28 天' 漂浮

我一直在試圖弄清楚如何做到這一點。 這是我設法實現的最接近的事情:

age_strength_model = data[['Water-Binder', 'Fly Ash', 'Age', 'Strength %']].copy()
ages = np.unique(age_strength_model['Age'].values)

# create table investigating the relationship between fly ash, age, and compressive strength
for a in ages:
  age_strength_model.query(f'`Fly Ash` == 0 & Age == {a}').groupby(['Water-Binder'])['Strength %'].transform(lambda x: x.mean())

然而,這只是向我展示了這些值,而不是將它們組織到一個數據集中,並且不適合將水粘合劑和粉煤灰組合在一起。 我將如何在這里達到預期的最終結果?

嘗試連接“Water-Binder”、“Fly Ash”、“Age”字段,然后分組:

data = [
    [0.43, 0.0, 3, 26.446759],
    [0.43, 0.0, 7, 44.444444],
    [0.43, 0.0, 28, 100.00000],
    [0.43, 0.0, 3, 11.316173],
    [0.43, 0.0, 7, 37.493929]
]

df = pd.DataFrame(data, columns= ['Water-Binder', 'Fly Ash', 'Age', 'Strength %'])
df['Water-Binder-Fly-Ash-Age'] = (df['Water-Binder'].astype(str)
                                  + '%'
                                  + df['Fly Ash'].astype(str)
                                  + '%'
                                  + df['Age'].astype(str))
df
   Water-Binder  Fly Ash  Age  Strength % Water-Binder-Fly-Ash
0          0.43      0.0    3   26.446759           0.43%0.0%3
1          0.43      0.0    7   44.444444           0.43%0.0%7
2          0.43      0.0   28  100.000000          0.43%0.0%28
3          0.43      0.0    3   11.316173           0.43%0.0%3
4          0.43      0.0    7   37.493929           0.43%0.0%7

# Creates a grouped df with the indices reset and 'Strength %' field renamed.
df_grouped = df.groupby(by='Water-Binder-Fly-Ash-Age').mean()['Strength %'].reset_index()
df_grouped.rename(columns={'Strength %': 'Mean Strength %'}, inplace=True)
df_grouped
  Water-Binder-Fly-Ash-Age  Mean Strength %
0              0.43%0.0%28       100.000000
1               0.43%0.0%3        18.881466
2               0.43%0.0%7        40.969186

如果要恢復 'Water-Binder'、'Fly Ash'、'Age' 字段,只需根據 '%' 分隔符將其拆分並“擴展”即可:

df_grouped[['Water-Binder', 'Fly Ash', 'Age']] = df['Water-Binder-Fly-Ash-Age'].str.split('%', expand=True)
df_grouped
  Water-Binder-Fly-Ash-Age  Mean Strength % Water-Binder  Fly Ash  Age
0              0.43%0.0%28       100.000000         0.43      0.0    3
1               0.43%0.0%3        18.881466         0.43      0.0    7
2               0.43%0.0%7        40.969186         0.43      0.0   28

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM