Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Convert a Pandas DataFrame into a single row DataFrame

I've seen similar questions but mine is more direct and abstract.

I have a dataframe with "n" rows, being "n" a small number.We can assume the index is just the row number. I would like to convert it to just one row.

So for example if I have

A,B,C,D,E
---------
1,2,3,4,5
6,7,8,9,10
11,12,13,14,5

I want as a result a dataframe with a single row:

A_1,B_1,C_1,D_1,E_1,A_2,B_2_,C_2,D_2,E_2,A_3,B_3,C_3,D_3,E_3
--------------------------
1,2,3,4,5,6,7,8,9,10,11,12,13,14,5

What would be the most idiomatic way to do this in Pandas?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Let's try this, using stack, to_frame, and T:

df.index = df.index + 1
df_out = df.stack()
df_out.index = df_out.index.map('{0[1]}_{0[0]}'.format)
df_out.to_frame().T

Output:

   A_1  B_1  C_1  D_1  E_1  A_2  B_2  C_2  D_2  E_2  A_3  B_3  C_3  D_3  E_3
0    1    2    3    4    5    6    7    8    9   10   11   12   13   14    5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...