将Pandas DataFrame转换为单行DataFrame [英] Convert a Pandas DataFrame into a single row DataFrame

查看:172
本文介绍了将Pandas DataFrame转换为单行DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过类似的问题,但是我的回答更直接,更抽象.

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

我有一个带有"n"行的数据帧,而"n"是一个小数字.我们可以假设索引只是行号. 我想将其转换为仅一行.

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.

例如,如果我有

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

在Pandas中最惯用的方法是什么?

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

推荐答案

让我们尝试使用stackto_frame和T:

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

输出:

   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

这篇关于将Pandas DataFrame转换为单行DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆