【问题标题】:Element-wise logical AND on indeterminate number of Pandas Series对不确定数量的 Pandas 系列进行元素逻辑与
【发布时间】:2014-06-18 13:14:08
【问题描述】:

假设我有一个 n 的列表/可迭代(其中 n 对函数未知)代表逻辑布尔索引的 Pandas 系列,我想按元素对它们进行 AND 并使用生成的系列来索引一个数据框。

目前我正在使用np.logical_and(x1,x2) 和一个 for 循环来执行此操作。我在使用itertools.izipzip 时运气不佳。 pandas.Series 对象似乎不喜欢被他们操作。

我现在一直在摸不着头脑,我可能没有看到为什么这似乎会导致一系列布尔值,但我在执行时得到IndexingError: Unalignable boolean Series key provided

有什么想法吗?我觉得既然这些是ndarray,就必须有一些明显干净的方法来做到这一点。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    假设我理解你,你可以使用logical_and.reduce。从系列列表开始:

    >>> ss = [pd.Series([ True, False,  True, False,  True]), pd.Series([False,  True,  True, False, False]), pd.Series([False, False,  True, False,  True]), pd.Series([False,  True,  True, False, False]), pd.Series([ True,  True,  True,  True, False])]
    

    看起来像

    >>> pd.DataFrame(ss)
           0      1     2      3      4
    0   True  False  True  False   True
    1  False   True  True  False  False
    2  False  False  True  False   True
    3  False   True  True  False  False
    4   True   True  True   True  False
    
    [5 rows x 5 columns]
    

    如果它是一个数据框,您可以跨列减少:

    >>> np.logical_and.reduce(ss)
    array([False, False,  True, False, False], dtype=bool)
    

    如果你想要另一个方向,或者传递axis=1

    记住你也可以使用anyall,例如

    >>> df = pd.DataFrame(ss)
    >>> df.all()
    0    False
    1    False
    2     True
    3    False
    4    False
    dtype: bool
    

    【讨论】:

      猜你喜欢
      • 2021-12-08
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      • 2019-04-26
      • 1970-01-01
      • 2012-01-20
      • 2017-07-28
      • 2023-03-21
      相关资源
      最近更新 更多