简体   繁体   中英

Indexing in pandas.DataFrame by list

I'd like to change values (into 'new value') of a column ('col_change') within a pd.DataFrame dependent on values in another column ('col_search'). For a single change I have a solution but I'm searching for a solution for more than one search values.

Example for single value as expected:

import numpy as np
import pandas as pd
my_array = np.array([[1,2,3,4,5,6,7,8,9,10],[11,22,33,44,55,66,77,88,99,100]])
my_df = pd.DataFrame(my_array, columns = ['col_change', 'col_search'])
my_df.col_change[my_df.col_search == 22] = 'new value'
print(my_df)

Example for multi value doesn't work like expected : The "in" operator doesn't work here.

import numpy as np
import pandas as pd
my_array = np.array([[1,2,3,4,5,6,7,8,9,10],[11,22,33,44,55,66,77,88,99,100]])
my_df = pd.DataFrame(my_array, columns = ['col_change', 'col_search'])
list_of_search = [33, 44, 55]
my_df.col_change[my_df.col_search in list_of_search] = 'new value'
print(my_df)

Using df.columns.isin

In [1083]: my_df.loc[my_df.col_search.isin([33, 44, 55]), 'col_change'] = 'new value'

In [1084]: my_df
Out[1084]: 
  col_change  col_search
0          1          11
1          2          22
2  new value          33
3  new value          44
4  new value          55
5          6          66
6          7          77
7          8          88
8          9          99
9         10         100

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