isin,str.contains和if条件之间的区别?

时间:2020-02-05 13:26:57

标签: python dataframe

我通常对是否要使用某些内容过滤数据框列项目感到困惑, 应该使用isin还是.str.containsif "aa" in df["column"]

请告诉我其中哪些在不同情况下使用?

3 个答案:

答案 0 :(得分:2)

isin

如果要检查一系列中多个字符串之一的出现,请使用isin

import pandas as pd                                                                                                      
things = pd.Series(['apple', 'banana', 'house', 'car'])                                                                                                                              
fruits = ['apple', 'banana', 'kiwi']                                                                                                                                            
things.isin(fruits)

输出:

0     True
1     True
2    False
3    False
dtype: bool

.str。包含

.str.contains的功能相同,但仅适用于一个字符串,并且还匹配字符串的一部分。

things.str.contains('apple')

输出:

0     True
1    False
2    False
3    False
dtype: bool
things.str.contains('app')

输出:

0     True
1    False
2    False
3    False
dtype: bool

A in series检查A是否在pd.Series的索引中:

"apple" in things                                                                                                                                                              
# Output: False

我们的things系列索引中没有“ apple”,这很清楚为什么:

> things
0     apple
1    banana
2     house
3       car
dtype: object

第一列描述了索引,因此我们可以对其进行检查:

0 in things                                                                                                                                                              
# Output: True

答案 1 :(得分:2)

我将尝试通过示例向您展示差异:

df = pd.DataFrame({'A': [4,8], 'B': ['hello toto','foo bar']})
df_1 = df[df['B'].str.contains("hello")]
df_2 = df.isin([4, "foo bar", "hello", "hello toto mamamia"])
df_3 = df.loc[df["B"] == "foo bar"] # implicit "if"

# df
   A            B
0  4   hello toto
1  8      foo bar

# df_1
   A           B
0  4  hello toto

# df_2
       A      B
0   True  False
1  False   True

# df_3
   A        B
1  8  foo bar

答案 2 :(得分:1)

isin if element x in list, return True else return False

str。包含if element x in string for string in list, return True else return False

如果if row['string'] == element x for row in df, return True else return False

最后一个等效于isin,其中list中只有1个元素。

基本上,ifisin用于检查某个列的值是否属于列表,而str.contains则用于搜索该列中的字符串以找到某个子字符串。 / p>

用法示例:

df
>>
  clientID   priceType
0  ER12312      member
1  ER24421    standard
2  WB44213      member
3  ER92932  discount15
4  WB02321    standard

我们希望所有客户支付会员价或标准价:

df[df.priceType.isin(['member','standard'])]
>>
  clientID priceType
0  ER12312    member
1  ER24421  standard
2  WB44213    member
4  WB02321  standard

如果我们需要所有“ ER”客户ID:

df[df.clientID.str.contains('ER')]
>>
  clientID   priceType
0  ER12312      member
1  ER24421    standard
3  ER92932  discount15