gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:24:31 27 4
gpt4 key购买 nike

我想知道我的数据框的某些列中是否存在特定字符串(每列一个不同的字符串)。据我了解isin()是为数据框编写的,但也适用于系列,而 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 Seriesmatches 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 astring of a Series or Index.

Return boolean Series or Index based on whether a given pattern orregex 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

关于python - Pandas :isin() 和 str.contains() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53079487/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com