Rename values not contained in a specific list

Viewed 108

I need your assistance in completeing the following task:

I would like to change all values of a column in pandas to 'others' expect specific 10 values.

Example :

Column a
1
2
3
4
5
5
5
6
6
6

List_not_change = ['1','2','3'] rest change to 'other'

Expected Result :

Column a
1
2
3
other
1 Answers

Use Series.isin for mask and replace by mask in DataFrame.loc:

#if values are integers
List_not_change = [1,2,3]

#if values are strings
#List_not_change = ['1','2','3']

df.loc[~df['Column a'].isin(List_not_change), 'Column a'] = 'other'
Related