[英]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.