input df:
A Jan.S1 Jan.S2 Feb.S1 Feb.S2
x 1 2 3 4
y 6 7 8 9
output df:
A month S1 S2
x Jan 1 2
x Feb 3 4
y Jan 6 7
y Feb 8 9
How can I make input become output format?
If you had a numeric value only after the '.' you could use pandas.wide_to_long.
As this is not the case, you can use a manual reshaping with a MultiIndex and stack:
out = (df
.set_index('A')
.set_axis(df.columns.drop('A').str.split('.', expand=True), axis=1)
.stack(0).rename_axis(['A', 'month'])
.reset_index()
)
output:
A month S1 S2
0 x Feb 3 4
1 x Jan 1 2
2 y Feb 8 9
3 y Jan 6 7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With