问题描述
我有一个需要重塑的数据框(以下示例)。我每行只需要一个唯一用户,但是现在,每个用户在数据框中都有两行,基于“测试日”列(基准线和D7)具有不同的值。我想根据测试日组的列名重命名值列('01。Tristeza Aparente)。因此,新值列将类似于“ Basel_Tristeza Aparente”和“ D7_01”。 Tristeza Aparente'
我在Pivot
和unstack
上准备的教程效果不佳,因为我没有尝试汇总数据。将用户折叠成一行时,我只需要不同的列。谢谢,请让我知道是否可以使这个问题更清楚
{'01. Tristeza Aparente': {0: 4.0,1: 4.0,2: 4.0,3: 2.0,4: 1.0,5: 0.0,6: 3.0},'02. Tristeza Expressa': {0: 6.0,1: 6.0,3: 0.0,4: 4.0,5: 3.0,6: 6.0},'group': {0: 'placebo',1: 'placebo',2: 'placebo',3: 'placebo',4: 'placebo',5: 'placebo',6: 'placebo'},'subject': {0: 1.0,1: nan,2: 2.0,3: nan,4: 3.0,5: nan,6: 4.0},'subjectedit': {0: 1.0,1: 1.0,'testday': {0: 'Basal',1: 'D7',2: 'Basal',3: 'D7',4: 'Basal',5: 'D7',6: 'Basal'}}
解决方法
这df['new_column'] = df['testday'] + '_' + '01. Tristeza Aparente'
是否可以解决您的问题?您还可以将其分配给现有列。
您可以pivot
f
并使用带有df = df.pivot(index=['group','subjectedit'],columns='testday')
df.columns = [f'{col[1]}_{col[0]}' for col in df.columns]
df
Out[1]:
Basal_01. Tristeza Aparente D7_01. Tristeza Aparente \
group subjectedit
placebo 1.0 4.0 4.0
2.0 4.0 2.0
3.0 1.0 0.0
4.0 3.0 NaN
Basal_02. Tristeza Expressa D7_02. Tristeza Expressa \
group subjectedit
placebo 1.0 6.0 6.0
2.0 4.0 0.0
3.0 4.0 3.0
4.0 6.0 NaN
Basal_subject D7_subject
group subjectedit
placebo 1.0 1.0 NaN
2.0 2.0 NaN
3.0 3.0 NaN
4.0 4.0 NaN
格式字符串的列来重命名列,但是请确保您使用的是最新版本的熊猫,因为枢轴在早期版本中存在问题。
{{1}}