Reputation: 1557
I'm kind of new to pandas
and I'm trying to perform some table manipulation. I'm not exactly sure how the action I'm looking for is called.
I have a pandas dataframe (the actual one is larger, but these are the cols I need to convert:
pr10 pr50 pr90
25.6214 30.2753 36.634
1.94509 3.84798 6.55111
0 0 0.00835
0 0 0.007279
And I want to convert it to:
pr10_0 pr50_0 pr90_0 pr10_1 pr50_1 pr90_1 pr10_2 pr50_2 pr90_2 pr10_3 pr50_3 pr90_3 pr10_4 pr50_4 pr90_4
25.6214 30.2753 36.634 1.94509 3.84798 6.55111 0 0 0.00835 0 0 0.007279 0.003505 0.007009 0.014764
How can I accomplish that?
Upvotes: 2
Views: 1443
Reputation: 9264
You could recreate the dataframe:
Create new columns from current dataframe
cols = [name+'_{}'.format(num // len(df.columns)) for num,name in enumerate(df.columns.tolist()*len(df))]
Create a new dataframe by flattening all the values from the original dataframe
pd.DataFrame(df.values.reshape(1,-1),columns=cols)
pr10_0 pr50_0 pr90_0 pr10_1 pr50_1 pr90_1 pr10_2 pr50_2 \
0 25.6214 30.2753 36.634 1.94509 3.84798 6.55111 0.0 0.0
pr90_2 pr10_3 pr50_3 pr90_3
0 0.00835 0.0 0.0 0.007279
Upvotes: 0
Reputation: 323226
Using stack
and join the multiple index
df1=df.stack().to_frame(0).T
df1.columns=df1.columns.map('{0[1]}_{0[0]}'.format)
df1
Out[445]:
pr10_0 pr50_0 pr90_0 pr10_1 pr50_1 pr90_1 pr10_2 pr50_2 \
0 25.6214 30.2753 36.634 1.94509 3.84798 6.55111 0.0 0.0
pr90_2 pr10_3 pr50_3 pr90_3
0 0.00835 0.0 0.0 0.007279
Upvotes: 1