简体   繁体   中英

partly reindex row indexes Pandas DataFrame

Need to reindex indexes which are separated by mask and leave unchanged all others indexes

Here is some example:

data = {'Name':['Tom', 'nick', 'krish', 'jack'], 
         'Age':[20, 21, 19, 18]} 
pd.DataFrame(data, index =[5,10,15,20])

separate by mask rows

age_mask = data['Age'] >= 20

tried to change indexes for mask rows somehow like here below

data[age_mask].index = data[age_mask].index + 1000

after execution all indexes stay unchanged.

     Name  Age
5     Tom   20
10   nick   21
15  krish   19
20   jack   18

and that's what I need to get

      Name  Age
1005  Tom    20
1010  nick   21
15    krish  19
20    jack   18

Use numpy.where and overwrite index values:

data.index = np.where(age_mask, data.index + 1000, data.index)

Or use Index.where with inverted mask by ~ :

data.index = data.index.where(~age_mask, data.index + 1000)

print (data)
     Name  Age
1005    Tom   20
1010   nick   21
15    krish   19
20     jack   18

Your solution should be changed:

data.index[age_mask] = data[age_mask].index + 1000
print (data)

But it return error:

TypeError: Index does not support mutable operations

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