pandas replace index, column name

1) just replace the index name

df.index = list

 

2) When adjusting the index, the following items should also be adjusted accordingly:

df.reindex(list)

Note that if an index that is not in df appears in the list , the following items will become nan

 

Example:

df=pd.DataFrame({'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]},columns=['a','b','c'],index=['11','22','33'])

 

print(df):

      a  b  c

11  1  4  7

22  2  5  8

33  3  6  9

 

df.index = ['44','55','66']

print(df):

      a  b  c

44  1  4  7

55  2  5  8

66  3  6  9

 

df=df.reindex(['22','11','44','33'])

print(df)

      a  b  c

22  2  5  8

11  1  4  7

44 NaN NaN NaN

33  3  6  9

 

3) Replace the columns

df.columns = ['a','b','c'] # Just replace the list with abc, the actual content has not changed

To achieve a reindex-like effect, you need to use df=df[[ 'c' , 'b' , 'a' ]]

 

 

4) Notes on index

If the top cell in the first column of excel is empty, the first column will become index after read_excel

If you are reading the sereis in the df , please note that the index will become 1,2,3,4,5... .

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325345251&siteId=291194637