![](/img/trans.png)
[英]Reshape pandas DataFrame from wide to long by splitting column names into variable and label
[英]Reshape dataframe in Pandas from long to wide format with new column names
我有一個需要重塑的數據框(示例如下)。 我只需要每行一個唯一用戶,但是,現在,每個用戶在數據框中都有兩行,基於“testday”列(基線和 D7)具有不同的值。 我想要的是根據 testday 組的列名重命名值列 ('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,
2: 4.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, 2: 2.0, 3: 2.0, 4: 3.0, 5: 3.0, 6: 4.0},
'testday': {0: 'Basal',
1: 'D7',
2: 'Basal',
3: 'D7',
4: 'Basal',
5: 'D7',
6: 'Basal'}}
這是df['new_column'] = df['testday'] + '_' + '01. Tristeza Aparente'
df['new_column'] = df['testday'] + '_' + '01. Tristeza Aparente'
會解決您的問題嗎? 您還可以將其分配給現有列。
您可以使用f
對數據框進行pivot
並使用格式化的字符串重命名列,但請確保您使用的是最新版本的 Pandas,因為早期版本的透視有問題。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.