📜  Pandas DataFrame.isin()

📅  最后修改于: 2020-10-29 03:09:46             🧑  作者: Mango

Pandas DataFrame.isin()

DataFrame.isin()方法的主要任务是选择特定列中具有特定(或多个)值的行。

句法

DataFrame.isin(values)

参数

values:可以是DataFrame,Series,Iterable或dict,并返回布尔值。

如果所有标签都匹配,它将返回一个真值。如果它由一个Series组成,那么它将是索引。

如果它由字典组成,则键必须是列名并且必须匹配。

如果它由DataFrame组成,则索引标签和列标签都必须匹配。

范例1:

import pandas as pd
#initializing dataframe
info = pd.DataFrame({'x': [1, 2], 'y': [3, 7]})
#check if the values of info are in the range(1,6)
p = info.isin(range(1,8))
print('DataFrame\n-----------\n',info)
print('\nDataFrame.isin(range(1,6))\n-----------\n',p)

输出:

DataFrame
-----------
xy
0  1  3
1  2  7

DataFrame.isin(range(1,6))
-----------
xy
0  TrueTrue
1  TrueTrue

范例2:

import pandas as pd 
data = pd.DataFrame({
    'EmpCode': ['Emp001', 'Emp002', 'Emp003', 'Emp004', 'Emp005'],
    'Name': ['Parker', 'Smith', 'Jones', 'Terry', 'Palin'],
    'Occupation': ['Tester', 'Developer', 'Statistician',
                   'Tester', 'Developer'],
    'Date Of Join': ['2019-01-17', '2019-01-26', '2019-01-29', '2019-02-02',
                     '2019-02-11'],
    'Age': [29, 22, 25, 38, 27]})

print("\nUseisin operator\n")
print(data.loc[data['Occupation'].isin(['Tester','Developer'])])
print("\nMultiple Conditions\n")
print(data.loc[(data['Occupation'] == 'Tester') |
                    (data['Name'] == 'John') &
                    (data['Age'] < 27)])

输出:

Use isin operator

EmpCodeNameOccupation                Date Of Join       Age
0  Emp001      Parker     Tester            2019-01-17     29
1  Emp002      Smith    Developer       2019-01-26     22
3  Emp004     Terry       Tester            2019-02-02   38
4  Emp005     Palin    Developer         2019-02-11   27

Multiple Conditions

EmpCode         Name      Occupation      Date Of Join    Age
0  Emp001      Parker     Tester           2019-01-17     29
3  Emp004      Terry       Tester           2019-02-02     38