Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按特定列的可能前缀列表筛选dataframe_Python_Python 3.x_Pandas - Fatal编程技术网

Python 按特定列的可能前缀列表筛选dataframe

Python 按特定列的可能前缀列表筛选dataframe,python,python-3.x,pandas,Python,Python 3.x,Pandas,我想做的是: options = ['abc', 'def'] df[any(df['a'].str.startswith(start) for start in options)] 我想应用一个筛选器,这样我只有在列“a”中具有以给定选项之一开头的值的条目 下一个代码可以工作,但我需要它与几个前缀选项一起工作 start = 'abc' df[df['a'].str.startswith(start)] 错误消息是 ValueError: The truth value of a Seri

我想做的是:

options = ['abc', 'def']
df[any(df['a'].str.startswith(start) for start in options)]
我想应用一个筛选器,这样我只有在列“a”中具有以给定选项之一开头的值的条目

下一个代码可以工作,但我需要它与几个前缀选项一起工作

start = 'abc'
df[df['a'].str.startswith(start)]
错误消息是

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
阅读,但不了解如何阅读

您可以尝试以下方法:

mask = np.array([df['a'].str.startswith(start) for start in options]).any(axis=1)
它为每个
开始
选项创建一个
系列
,并沿相应行应用
任何


您之所以会收到此错误,是因为内置程序需要一个
bool
s列表,但正如错误消息所示,“多值对象的真值不明确”,因此您更需要使用数组感知
any

您可以将一组选项传递给startswith

df = pd.DataFrame({'a': ['abcd', 'def5', 'xabc', '5abc1', '9def', 'defabcb']})
options = ['abc', 'def']
df[df.a.str.startswith(tuple(options))]
你得到

    a
0   abcd
1   def5
5   defabcb
还有一个解决方案:

# extract all possible values for 'a' column
all_a_values = df['a'].unique()
# filter 'a' column values by my criteria
accepted_a_values = [x for x in all_a_values if any([str(x).startswith(prefix) for prefix in options])]
# apply filter
df = df[df['a'].isin(accepted_a_values))]
从这里开始:


@Vaishali提供的解决方案是最简单、最符合逻辑的,但我也需要接受的_a_值列表来进行迭代。问题中没有提到这一点,因此我认为她的答案是正确的。

请向我们展示您的数据集!谢谢你的解释!但是Series的any不是返回一个匹配项而不是bool结果吗?你是说
Series.any()
?如果序列的任何元素的计算结果为
True
,则返回
True
,否则返回
False
。是的,我感到困惑,因为函数的名称相同,行为略有不同。。。尽管将any([…])视为获取数组中任何真值的函数,但它是相同的。谢谢是的,没错。反过来,您需要跨多个
系列
行应用
any
。幸运的是,将一个元组传递给
startswith
(由Vaishali建议)是一个更简单、更合理的解决方案。很抱歉,您的解决方案不符合其他方面的要求,所以最后我用了另一种方式—这就是我取消标记它的原因。我也会补充我的答案。找出我做其他事情的原因,这不是你的解决方案的限制,所以我接受它。非常感谢。