Pandas 数据帧isin()方法

原文:https://www.studytonight.com/pandas/pandas-dataframe-isin-method

在本教程中,我们将讨论和学习 PandasDataFrame.isin()的方法。此方法检查数据帧中的每个元素是否包含在指定的值中。当此方法应用于数据帧时,它返回布尔值的数据帧。如果数据帧由组成,则元素以指定值出现,否则显示

下面是DataFrame.isin()方法的语法。

句法

DataFrame.isin(values)

因素

值:可以是可迭代、序列、数据帧或字典。如果值是一个序列,那就是索引。如果值是字典,则键必须是列名,列名必须匹配。如果值是数据帧,则索引和列标签必须匹配。

示例 1:使用DataFrame.isin()方法检查值

这里,我们使用DataFrame.isin()方法用list 检查数据帧。如果数据帧中的每个值都出现在list中,则返回真的布尔值数据帧,否则返回假的。见下面的例子。

import pandas as pd
#creating the DataFrame
df = pd.DataFrame({'a': [2, 4], 'b': [2, 0], 'c':[3, 5]})
print("-----The DataFrame is----")
print(df)
print("----------------------")
df_1=df.isin([2,3])
print(df_1)

一旦我们运行该程序,我们将获得以下输出。

-数据帧为- a b c 0 2 2 3 1 4 0 5 - a b c 0 真真真 1 假假假

示例 2:使用DataFrame.isin()方法检查值

这里,我们使用DataFrame.isin()方法用Series 检查数据帧。如果数据帧中的每个值都出现在Series 中,则返回真的布尔值数据帧,否则返回假的。见下面的例子。

import pandas as pd
#creating the DataFrame
df = pd.DataFrame({'a': [2, 4], 'b': [2, 0], 'c':[3, 5]})
print("-----The DataFrame is----")
print(df)
print("----------------------")
series=pd.Series([2,0,3])
df_1=df.isin(series)
print(df_1)

一旦我们运行该程序,我们将获得以下输出。

-数据帧为- a b c 0 2 2 3 1 4 0 5 - a b c 0 真真假假 1 假真假假

示例 3:使用DataFrame.isin()方法检查值

这里,我们使用DataFrame.isin()方法用other DataFrame 检查数据帧。如果数据帧中的每个值都出现在other DataFrame 中,则返回真的布尔值数据帧,否则返回假的。见下面的例子。

import pandas as pd
#creating the DataFrame
df_1= pd.DataFrame({'a': [2, 4], 'b': [2, 0], 'c':[3, 5]})
print("-----The DataFrame is----")
print(df_1)
print("----------------------")
df_2= pd.DataFrame({'a': [0, 4], 'b': [1, 0], 'c':[3, 2]})
print(df_2)
print("----------------------")
print(df_1.isin(df_2))

一旦我们运行该程序,我们将获得以下输出。

-数据帧为- a b c 0 2 2 3 1 4 0 5 - a b c 0 1 3 1 4 0 2 - a b c 0 假真 1 真真假

示例 4:使用DataFrame.isin()方法检查值

这里,我们使用DataFrame.isin()方法用dictionary 检查数据帧。如果数据帧中的每个值都出现在dictionary中,则返回布尔值的数据帧,否则返回假。见下面的例子。

import pandas as pd
#creating the DataFrame
df_1= pd.DataFrame({'a': [2, 4], 'b': [2, 0], 'c':[3, 5]})
print("-----The DataFrame is----")
print(df_1)
print("----------------------")
dict = {'a': [2, 1]}
print(dict)
print("----------------------")
print(df_1.isin(dict))

一旦我们运行该程序,我们将获得以下输出。

-数据帧为- a b c 0 2 2 3 1 4 0 5 - { ' a ':【2,1】} - a b c 0 真假假 1 假假假假

结论:

在本教程中,我们学习了 PandasDataFrame.isin()方法。我们学习了语法,并通过示例将该方法应用于数据帧。