且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将Pandas DataFrame的行转换为列标题,

更新时间:2021-09-07 18:28:33

In [21]: df = pd.DataFrame([(1,2,3), ('foo','bar','baz'), (4,5,6)])

In [22]: df
Out[22]: 
     0    1    2
0    1    2    3
1  foo  bar  baz
2    4    5    6

将列标签设置为等于第二行(索引位置1)中的值:

Set the column labels to equal the values in the 2nd row (index location 1):

In [23]: df.columns = df.iloc[1]

如果索引具有唯一标签,则可以使用以下命令删除第二行:

If the index has unique labels, you can drop the 2nd row using:

In [24]: df.drop(df.index[1])
Out[24]: 
1 foo bar baz
0   1   2   3
2   4   5   6

如果索引不是唯一的,则可以使用:

If the index is not unique, you could use:

In [133]: df.iloc[pd.RangeIndex(len(df)).drop(1)]
Out[133]: 
1 foo bar baz
0   1   2   3
2   4   5   6

使用df.drop(df.index[1])删除具有与第二行相同标签的 all 行.由于非唯一索引可能会导致像这样的绊脚石(或潜在的错误),因此通常***注意索引的唯一性(即使Pandas不需要它).

Using df.drop(df.index[1]) removes all rows with the same label as the second row. Because non-unique indexes can lead to stumbling blocks (or potential bugs) like this, it's often better to take care that the index is unique (even though Pandas does not require it).