【问题标题】:numpy where search multiple conditions with a precomputed seriesnumpy where 使用预先计算的系列搜索多个条件
【发布时间】:2021-07-01 16:38:03
【问题描述】:

我有一个包含多个系列的列表,其中包含布尔值和熊猫数据框。列表中的系列数量各不相同。

s1 = {Series: (4,)} (0, True) (1, True) (2, True) (3, True)
s2 = {Series: (4,)} (0, True) (1, True) (2, True) (3, False)
list_with_series = [s1, s2]

df = {DataFrame: (4, 8)}

我想使用 numpy.where 向 DataFrame 添加一列,其标签如下:

df['Tag'] = numpy.where(' & '.join(list_with_series), 'Tag_name', '')

当我尝试加入系列时,我收到此错误:

TypeError: sequence item 0: expected str instance, Series found

我不能直接指定像numpy.where(s1 & s2) 这样的系列,因为系列的数量是动态的。 我也尝试使用 numpy,因为它占用的内存较少。

在 DataFrame 中匹配和标记行的最佳方法是什么,而不是使用带有布尔值的预计算系列?在这种情况下甚至可以使用 numpy 吗?

谢谢!

【问题讨论】:

  • 你贴的代码是python吗?我不明白这是什么s1 = {Series: (4,)} (0, True) (1, True) (2, True) (3, True)。您可以发布工作代码吗?
  • 这是它在 pycharm 调试器中的样子。它是系列的代表,我猜它是魔术 str 方法的回归。对我们来说,它是一个包含 4 个布尔元素的系列
  • 哦,好吧。感谢您的澄清。明白了:)

标签: python pandas numpy


【解决方案1】:

在这种情况下,当您编写 ' & '.join(...) 时,期望您将传递字符串,而不是系列。这是错误。

在这种情况下,您可以使用:

import numpy as np

np.logical_and.reduce([s.values for s in list_with_series])

【讨论】:

  • 有没有办法使用逻辑和多个系列之间只得到一个,其中:True and True = True;真假=假?它应该可以帮助我将多个系列减少到只有一个并在 np.where 函数中使用它。
  • 哦,我明白了。这正是你给我的建议
猜你喜欢
  • 2021-04-08
  • 2014-02-19
  • 1970-01-01
  • 2013-04-26
  • 1970-01-01
  • 2019-12-25
  • 1970-01-01
  • 2012-12-11
  • 1970-01-01
相关资源
最近更新 更多