简体   繁体   中英

How can i change the numbering of the index in a pivot table (python)

I have gathered my data into a pivot table of the following form:

movie_id  1     2     3     4     5     ...  
user_id                                 ...                              
1          1.0   0.0   1.0   0.0   0.0  ...   
2          1.0   NaN   NaN   NaN   NaN  ...   
3          NaN   NaN   NaN   NaN   NaN  ...   
4          NaN   NaN   NaN   NaN   NaN  ...
5          1.0   0.0   NaN   NaN   NaN  ...  
6          1.0   NaN   ....
.          .....
.
.
943

What i need is my (user_id) index to change its numbering from 1-943 to 943-1886 so that i can run some algortihms later, in which the movie ids will be different than the user ids. Is that possible in some way?

edited console:

movie_id  1     2     3     4     5     ...   943 
944       1.0   0.0   1.0   0.0   0.0  ...   0.0   
945       1.0   0.0   0.0   0.0   0.0  ...   0.0   
946       0.0   0.0   0.0 
.
.
.

Look at this

>>> import pandas as pd
>>> df = pd.DataFrame([(1, 10), (2, 11), (3, 12), (4, 13), (5, 14)], columns=['movie_id', 'user_id'])
>>> df
   movie_id  user_id
0         1       10
1         2       11
2         3       12
3         4       13
4         5       14
>>> df.index = range(943, 948)
>>> df
     movie_id  user_id
943         1       10
944         2       11
945         3       12
946         4       13
947         5       14

If you want to rename your index column, just do this

>>> df.index.names = ['my_index']
>>> df
          movie_id  user_id
my_index                   
943              1       10
944              2       11
945              3       12
946              4       13
947              5       14

Alternative, you can do this

>>> df.index = pd.RangeIndex(start=943, stop=948, step=1, name='my_index')
>>> df
          movie_id  user_id
my_index                   
943              1       10
944              2       11
945              3       12
946              4       13
947              5       14

my_pivot_table.index = range(943,1886) worked in changing the numbering of the pivot table's index!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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