Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

pandas - how to make two rows to single row based on index in python

I am trying to convert data frame with two rows as single row. here i am placing tables for better understanding.

This is my actual output

enter image description here

how to convert above table to single row (see below table)

enter image description here

question from:https://stackoverflow.com/questions/65936142/how-to-make-two-rows-to-single-row-based-on-index-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use DataFrame.set_index with DataFrame.stack for MultiIndex Series, convert to one column DataFrame by Series.to_frame and transpose for one row DataFrame, last flatten MultiIndex by join:

df1 = s.set_index('Gender').stack().to_frame().T
df1.columns = df1.columns.map(lambda x: f'{x[0]} {x[1]}')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...