Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a new column from other column's string?

Tags:

python

pandas

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?

like image 422
JGQ Avatar asked Dec 14 '25 22:12

JGQ


1 Answers

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
like image 119
mozway Avatar answered Dec 16 '25 14:12

mozway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!