Pandas: 检查 Series of strings 是否在 Series with list of strings
Pandas: Check if Series of strings is in Series with list of strings
我正在寻找一种方法来确定 pandas
字符串系列是否包含在另一个系列的字符串列表的值中。
最好是单行 - 我知道我可以通过遍历行并建立一个新系列来解决这个问题。
示例:
import pandas as pd
df = pd.DataFrame([
{'value': 'foo', 'accepted_values': ['foo', 'bar']},
{'value': 'bar', 'accepted_values': ['foo']},
])
期望的输出是
pd.Series([True, False])
因为'foo'
在['foo', 'bar']
,但是'bar'
不在['foo']
我试过的:
df['value'].isin(df['accepted_values'])
,但这给了我 [False, False]
谢谢!
您可以将 apply
与 in
一起使用:
df.apply(lambda r: r.value in r.accepted_values, axis=1)
0 True
1 False
我正在寻找一种方法来确定 pandas
字符串系列是否包含在另一个系列的字符串列表的值中。
最好是单行 - 我知道我可以通过遍历行并建立一个新系列来解决这个问题。
示例:
import pandas as pd
df = pd.DataFrame([
{'value': 'foo', 'accepted_values': ['foo', 'bar']},
{'value': 'bar', 'accepted_values': ['foo']},
])
期望的输出是
pd.Series([True, False])
因为'foo'
在['foo', 'bar']
,但是'bar'
不在['foo']
我试过的:
df['value'].isin(df['accepted_values'])
,但这给了我[False, False]
谢谢!
您可以将 apply
与 in
一起使用:
df.apply(lambda r: r.value in r.accepted_values, axis=1)
0 True
1 False