我通常对是否要使用某些内容过滤数据框列项目感到困惑,
应该使用isin
还是.str.contains
或if "aa" in df["column"]
?
请告诉我其中哪些在不同情况下使用?
答案 0 :(得分:2)
如果要检查一系列值中多个字符串之一的出现,请使用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.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个元素。
基本上,if
和isin
用于检查某个列的值是否属于列表,而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