Pandas的isin()方法有助于在给定的DataFrame中搜索输入的数值集。我们将讨论Pandas,它的isin()方法,以及它的例子。
什么是Python中的Pandas?
Pandas 是 Python 的标准数据框架模块。如果你在 Python 中处理表格数据,你几乎应该使用 Pandas。
它提供了一个非常有效的数据结构和工具来进行数据分析。Pandas是一个用于数据科学和分析的Python模块,运行在NumPy之上。Pandas的基本数据结构中的DataFrame允许我们在一个二维结构中存储和改变表格式数据。
什么是DataFrame?
最基本和最广泛使用的数据结构是DataFrame,它是存储数据的标准方式。DataFrame将数据组织在行和列中,就像一个SQL表或电子表格数据库。我们可以将我们的自定义数据转换成DataFrame,或者从CSV、tsv、Excel、SQL数据库或其他来源导入数据。
什么是Pandas Isin()函数?
isin()函数检查所提供的值是否存在于Dataframe中。这个函数返回一个布尔值的DataFrame。DataFrame看起来和原来的一样,没有被改变。尽管如此,如果数据框架元素是指定的元素之一,则原始值被替换为True,否则被改变为False。
Isin()方法的例子
例1:
import pandas as pd
data = pd.DataFrame({
'Name': ['A', 'B', 'C', 'D'],
'Roll number': [25, 40, 23, 22],
'Height': ['169', '173', '173', '178']
})
heights_to_filter = ['173', '169', '177']
result = data.isin(heights_to_filter)
print(result)
输出
Name Roll number Height
0 False False True
1 False False True
2 False False True
3 False False False
例2:
import pandas as pd
data = pd.DataFrame({
'Name': ['A', 'B', 'C', 'D'],
'Age': [25, 45, 23, 32],
'Favorite Subject': ['Math', 'Science', 'Science', 'English']
})
dict_data_to_filter = {'Name': ['B', 'D'], 'Department': ['Science']}
result = data.isin(dict_data_to_filter)
print(result)
输出
Name Age Favorite Subject
0 False False False
1 True False False
2 False False False
3 True False False
例3:
import pandas as pd
data = pd.DataFrame({
'Name': ['A', 'B', 'C', 'D'],
'Age': [25, 45, 23, 32],
'Department': ['29', '35', '35', '40']
})
series_data = pd.Series(['A', 'C', 'B', 'D'])
result = data.isin(series_data)
print(result)
输出
Name Age Department
0 True False
1 False False
2 False False
3 True False
例4:
import pandas as pd
data = pd.DataFrame({
'Name': ['A', 'B', 'C', 'D'],
'Roll number': [25, 45, 23, 32],
'House': ['Blue', 'Green', 'Green', 'Yellow']
})
df = pd.DataFrame({
'Name': ['A', 'B', 'C', 'D'],
'Roll number': [25, 45, 23, 32],
'House': ['Blue', 'Green', 'Green', 'Yellow']
})
result = data.isin(df)
print(result)
print()
df = pd.DataFrame({
'Name': ['A', 'B', 'C', 'D'],
'Roll number': [25, 45, 23, 32],
'House': ['Blue', 'Green', 'Green', 'Yellow']
})
result = data.isin(df)
print(result)
输出
Name Roll number House
0 True True True
1 True True True
2 True True True
3 True True True
Name Roll number House
0 True True True
1 True True True
2 True True True
3 True True True
总结
我们讨论了Python中的Pandas,DataFrame,Pandas isin()函数,以及一些isin()方法的例子。isin()方法是用来获取布尔数据框架,告诉人们哪些输入值存在于数据框架中。