Pandas:isin() 和str.contains() 有什么区别?

Pandas: What is the difference between isin() and str.contains()?

我想知道我的数据框的某些列中是否存在特定字符串(每列不同的字符串)。 据我了解,isin() is written for dataframes but can work for Series as well, while str.contains() 更适合 Series。

我不明白我应该如何在两者之间做出选择。 (我搜索了类似的问题,但没有找到关于如何在两者之间进行选择的任何解释。)

.isin 检查列中的每个值是否包含在任意值列表中。大致相当于 value in [value1, value2].

str.contains 检查列中的每个值中是否包含任意值。大致相当于 substring in large_string.

换句话说,.isin 按列工作并且适用于所有数据类型。 str.contains 按元素工作,仅在处理字符串(或可以表示为字符串的值)时才有意义。

来自官方文档:

Series.isin(values)

Check whether values are contained in Series. Return a boolean Series showing whether each element in the Series matches an element in the passed sequence of values exactly.


Series.str.contains(pat, case=True, flags=0, na=nan,** **regex=True)

Test if pattern or regex is contained within a string of a Series or Index.

Return boolean Series or Index based on whether a given pattern or regex is contained within a string of a Series or Index.

示例:

print(df)
#     a
# 0  aa
# 1  ba
# 2  ca

print(df[df['a'].isin(['aa', 'ca'])])
#     a
# 0  aa
# 2  ca

print(df[df['a'].str.contains('b')])
#     a
# 1  ba