The Pandas Index function isin() used to determine whether each specified set of values found in Index object. It returns an array of boolean value element-wise that has same length of source Index object.
1 Index.isin(values, level = None)
values : It is set or list to match in the Index object.
level : It is string or integer that specifies the index level to use(applicable with MultiIndex).
1 import pandas as pd
2
3 index = pd.Index([67, 10, 24, 15, 68, 98])
4
5 print('The original Index object :')
6 print(index)
7
8 res = index.isin([15, 20])
9 print('The Index matches element-wise :')
10 print(res)
In the above example, an Index object is created by passing an array. A isin() function is called by passing a set of values that matches elements of Index. It returns boolean array where specified value match, the element value will be True, otherwise False. The result is assign to variable that will be printed on console.
1 The original Index object :
2 Index([67, 10, 24, 15, 68, 98], dtype='int64')
3
4 The Index matches element-wise :
5 [False False False True False False]
isin() with values and level
isin() with values and level
1 import pandas as pd
2
3 index = pd.MultiIndex.from_arrays([[10, 20, 30],
4 ['x', 'y', 'z']],
5 names = ('number', 'label'))
6
7 print('The original Index object :')
8 print(index)
9
10 res = index.isin(['x', 'z'], level = 'label')
11 print('The Index matches element-wise :')
12 print(res)
In the above example, a MultiIndex object is created by passing an array and names. A isin() function is called by set of values and level. It returns boolean array element-wise that includes Ture, if match found in specified level, otherwise False.
1 The original Index object :
2 MultiIndex([(10, 'x'),
3 (20, 'y'),
4 (30, 'z')],
5 names=['number', 'label'])
6
7 The Index matches element-wise :
8 [ True False True]
isin() with datetime
1 import pandas as pd
2
3 dates = ['2020-01-01', '2020-01-02', '2020-01-03']
4 index = pd.to_datetime(dates)
5
6 print('The original Index object :')
7 print(index)
8
9 res = index.isin(['2020-01-01', '2020-01-03'])
10 print('The Index matches element-wise :')
11 print(res)
In the above example, a Datetime object is created by passing an array of dates. A isin() function is called that returns boolean value element-wise for the matching value with specified value.
1 The original Index object :
2 DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03'], dtype='datetime64[ns]', freq=None)
3
4 The Index matches element-wise :
5 [ True False True]
Related options for your search