Issue
(Please help me to rephrase the title. I looked at questions with similar titles but they are not asking the same thing.)
I have a dataframe like this:
A B C
0 1 4 7
1 2 5 8
2 3 6 9
(the first column is indexes and not important)
I need to transform it so it ends up like this:
A A-1 A-2 B B-1 B-2 C C-1 C-2
1 2 3 4 5 6 7 8 9
I know about DataFrame.T
which seems one step in the right direction, but how to programatically change the column headers, and move the rows "besides each other" to make it a single row?
Solution
First use DataFrame.unstack
with convert values to one columns DataFrame by Series.to_frame
and transpose, last flatten MultiIndex in list comprehension with if-else
for expected ouput:
df1 = df.unstack().to_frame().T
df1.columns = [a if b == 0 else f'{a}-{b}' for a, b in df1.columns]
print (df1)
A A-1 A-2 B B-1 B-2 C C-1 C-2
0 1 2 3 4 5 6 7 8 9
Answered By - jezrael
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.