发布于 3年前

Pandas修改dataframe的index

1、仅修改index名称

直接对dataframe的index赋值新的index名即可

df.index = newindex

示例:

df=pd.DataFrame({'c1':[1,2,3],'c2':[4,5,6],'c3':[7,8,9]},columns=['c1','c2','c3'],index=['1','2','3'])
print(df):
  c1 c2 c3
1 1  4  7
2 2  5  8
3 3  6  9
df.index = ['4','5','6']
print(df):
 c1 c2  c3
4 1  4  7
5 2  5  8
6 3  6  9

2、修改index顺序

df.reindex(newindex)

修改index顺序,如果newindex含有不存在的index,则新的index所有的项目值为nan。

df=df.reindex(['2','1','4','3'])
print(df)
   c1 c2 c3
2  2  5  8
1  1  4  7
4  NaN  NaN  NaN
3  3  6  9
©2020 edoou.com   京ICP备16001874号-3