Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何按索引将行旋转为列?_Python 3.x_Pandas - Fatal编程技术网

Python 3.x 如何按索引将行旋转为列?

Python 3.x 如何按索引将行旋转为列?,python-3.x,pandas,Python 3.x,Pandas,我有一个看起来像这样的数据帧: title answer 0 aa zz 1 bb xx 2 cc yy 3 dd ll 我希望按索引值进行旋转,并将行重置为索引和值,仅针对两行,如下所示: bb cc 0 xx yy 我该怎么做 我试过转置: df[['title','answer']].T 但这会将整数值放在列标题中,并且不确定如何按索引号进行选择 IIUC 我们可

我有一个看起来像这样的数据帧:

  title      answer
0  aa         zz
1  bb         xx
2  cc         yy
3  dd         ll
我希望按索引值进行旋转,并将行重置为索引和值,仅针对两行,如下所示:

    bb       cc
0   xx       yy
我该怎么做

我试过转置:

df[['title','answer']].T
但这会将整数值放在列标题中,并且不确定如何按索引号进行选择

IIUC

我们可以将
title
设置为索引,然后进行转置,得到整数的原因是您在索引上的转置

df_new = df.set_index('title').T

print(df_new)

title   aa  bb  cc  dd
answer  zz  xx  yy  ll
如果还想删除索引,请执行以下操作:

df_new = df.set_index('title').T.reset_index(drop=True)
df_new.columns.name = ''


@anky_91使用df.to_numpy()非常好这如何处理多个列?它会推断出第一列作为索引吗?@RustyShackleford你是最受欢迎的我的朋友,快乐编码:)
print(df_new)
   aa  bb  cc  dd
0  zz  xx  yy  ll