Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas replace indexes of rows according to a dictionary [closed]

I have a pandas dataframe called df:

             1   2   3   4   5   6   7   8   9   10
dog   jumps   1   1   1   1   1   1   0   1   1   1
      fox     1   1   1   1   1   1   0   0   1   1
      the     1   1   1   1   1   1   1   0   1   1
      dog     1   1   1   1   1   1   0   0   1   1
      over    1   1   1   1   1   1   0   0   1   1
fox   jumps   1   1   1   1   1   1   0   1   1   1
      fox     1   1   1   1   1   1   0   0   1   1
      the     1   1   1   1   1   1   1   0   1   1
      dog     1   1   1   1   1   1   0   0   1   1
      over    1   1   1   1   1   1   0   0   1   1
jumps jumps   1   1   1   1   1   1   0   0   1   0
      fox     1   1   1   1   1   1   1   0   1   0
      the     1   0   1   1   1   1   0   0   1   0
      dog     1   1   1   1   1   1   1   0   1   0
      over    1   0   1   1   1   0   0   1   1   0
over  jumps   1   1   0   1   0   1   1   0   1   0
      fox     1   1   1   1   1   1   0   0   1   0
      the     1   0   1   1   1   0   0   1   1   0
      dog     1   1   1   1   1   1   0   0   1   0
      over    1   1   1   1   1   1   0   0   1   0
the   jumps   1   1   0   1   1   1   0   0   1   0
      fox     1   1   1   1   1   1   0   1   1   0
      the     1   1   1   1   1   1   0   0   1   0
      dog     1   1   1   1   1   1   0   1   1   0
      over    1   1   0   1   0   1   1   0   1   0

I have the following dictionary:

dic = {'dog': 1, 'fox': 1, 'the': 2, 'over': 2, 'jumps': 0}

I want to replace the values of indexes with their respective values from the dic.

I have tried the following approach:

df.index.levels[0][0] = 'integer value'

but this doesn't work and it gives me the error:

TypeError: Index does not support mutable operations

Also the pandas rename function is also not working

Any idea of how to do this in the most efficient and clean way. Any suggestions will be highly appreciated.

like image 587
sshussain270 Avatar asked Oct 20 '25 09:10

sshussain270


1 Answers

I think rename still work

df.rename(index=dic)
Out[1311]: 
     1  2  3  4  5  6  7  8  9  10                               
1 0  1  1  1  1  1  1  0  1  1   1
  1  1  1  1  1  1  1  0  0  1   1
  2  1  1  1  1  1  1  1  0  1   1
  1  1  1  1  1  1  1  0  0  1   1
  2  1  1  1  1  1  1  0  0  1   1
  0  1  1  1  1  1  1  0  1  1   1
  1  1  1  1  1  1  1  0  0  1   1
  2  1  1  1  1  1  1  1  0  1   1
  1  1  1  1  1  1  1  0  0  1   1
  2  1  1  1  1  1  1  0  0  1   1
like image 82
BENY Avatar answered Oct 21 '25 23:10

BENY