【问题标题】:Filter dataframe by a list of possible prefixes for specific column通过特定列的可能前缀列表过滤数据框
【发布时间】:2019-02-04 15:48:01
【问题描述】:

我想做的是:

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().

阅读Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(),但不了解如何操作。

【问题讨论】:

  • 请向我们展示您的数据集!

标签: python python-3.x pandas


【解决方案1】:

您可以将一组选项传递给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

【讨论】:

  • 抱歉,您的解决方案有其他问题,所以最后我用另一种方式做了 - 这就是我取消标记的原因。我也会添加我的答案。
  • 找出了我做其他事情的原因,这不是你的解决方案的限制,所以我接受了。谢谢!
【解决方案2】:

你可以试试这个:

mask = np.array([df['a'].str.startswith(start) for start in options]).any(axis=1)

它为每个start 选项创建一个Series,并沿相应的行应用any

您收到错误是因为 built-in 需要 bools 的列表,但错误消息表明“多值对象的真值不明确”,因此您需要使用数组感知 @ 987654326@。

【讨论】:

  • 感谢您的解释!但是 Series 不返回匹配项之一而不是 bool 结果吗?
  • 你的意思是Series.any()?如果 Series 的任何元素的计算结果为 True,则返回 True,否则返回 False
  • 是的,我很困惑,因为函数具有相同的名称并且行为略有不同...尽管将 any([...]) 视为获取任何 True 值的函数数组,是一样的。谢谢!
  • 是的,完全正确。反过来,您更需要的是在多个 Series 中逐行应用 any。幸运的是,通过将元组传递给startswith(由 Vaishali 建议)存在更简单、更合理的解决方案。
【解决方案3】:

另一种解决方案:

# 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))]

从这里获取:remove rows and ValueError Arrays were different lengths

@Vaishali 提供的解决方案是最简单和合乎逻辑的,但我也需要 accepted_a_values 列表来迭代槽。问题中没有提到这一点,所以我将她的答案标记为正确。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多