首先比較由iat
與Day
列中選擇的Day
第一值和與cumsum
創建新列。然後使用pivot
或set_index
+ unstack
,最後加add_suffix
:
df['col'] = df['Day'].eq(df['Day'].iat[0]).cumsum()
df = df.pivot(index='Day', columns='col', values='Total').add_prefix('Total')
print (df)
col Total1 Total2
Day
Fri 60 47
Mon 73 46
Sat 41 42
Sun 44 43
Thu 47 56
Tue 66 67
Wed 54 51
另一種解決方案:
df['col'] = df['Day'].eq(df['Day'].iat[0]).cumsum()
df = df.set_index(['Day', 'col'])['Total'].unstack().add_prefix('Total')
print (df)
col Total1 Total2
Day
Fri 60 47
Mon 73 46
Sat 41 42
Sun 44 43
Thu 47 56
Tue 66 67
Wed 54 51
如果想通過days
需要ordered
categorical
排序指數:如果需要原始排序
days = ['Sun', 'Mon','Tue', 'Wed', 'Thu', 'Fri', 'Sat' ]
df['Day'] = df['Day'].astype('category', categories=days, ordered=True)
df['col'] = df['Day'].eq(df['Day'].iat[0]).cumsum()
df = df.set_index(['Day', 'col'])['Total'].unstack().add_prefix('Total')
print (df)
col Total1 Total2
Day
Sun 44 43
Mon 73 46
Tue 66 67
Wed 54 51
Thu 47 56
Fri 60 47
Sat 41 42
使用reindex_axis
:
df['col'] = df['Day'].eq(df['Day'].iat[0]).cumsum()
a = df.loc[df['col'] == 1, 'Day']
df = df.set_index(['Day', 'col'])['Total'].unstack()
.add_prefix('Total')
.reindex_axis(a, axis=0)
.reset_index()
.rename_axis(None, axis=1)
print (df)
Day Total1 Total2
0 Tue 66 67
1 Wed 54 51
2 Thu 47 56
3 Fri 60 47
4 Sat 41 42
5 Sun 44 43
6 Mon 73 46