简体   繁体   English

重置pandas数据帧的列索引

[英]Reset column index of pandas dataframe

Is it possible to reset columns so they becomes first row of DataFrame . 是否可以重置列,使它们成为DataFrame第一行。 For example, 例如,

import pandas as pd

df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
   a  b
0  1  4
1  2  5
2  3  6

Desired ouput, 期望的输出,

df2 = df.reset_column() ???
   0  1
0  a  b
1  1  4
2  2  5
3  3  6

Can also chain reset.index 也可以链接reset.index

df.T.reset_index().T.reset_index(drop=True)

    0   1
0   a   b
1   1   4
2   2   5
3   3   6

Use 采用

In [57]: pd.DataFrame(np.vstack([df.columns, df]))
Out[57]:
   0  1
0  a  b
1  1  4
2  2  5
3  3  6

Inserting column names at the first row and resetting the indices. 在第一行插入列名并重置索引。

import pandas as pd

df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})

df.loc[-1] = df.columns
df.index = df.index + 1
df = df.sort_index()
df.columns = [0,1]
df

    0   1
0   a   b
1   1   4
2   2   5
3   3   6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM