【问题标题】:Numpy- how to create a boolean array with row and column indicesNumpy-如何创建具有行和列索引的布尔数组
【发布时间】:2021-11-29 00:17:03
【问题描述】:

我正在使用 scipy 中的 argrelextrema 来识别我的数据中的峰值。数据看起来像这样:

现在 argrelextrema 为我找到数据中的峰值并输出两个数组(行和列索引)。

argrelextrema(df.values, np.greater, axis=0,order=1)

现在,从我的原始数据中,我想创建一个布尔数组,其中峰值被标识为 True,其余的为 False

类似这样的东西(仅插图)。

通常我会用 np.where 实现类似上述的效果,但由于我现在有行和列索引,我没有找到如何将它与 np.where 子句一起使用的方法。

另外,如果可能的话,我想要一个矢量化解决方案。

【问题讨论】:

    标签: python pandas numpy boolean


    【解决方案1】:

    正如argrelextrema 指出的那样,返回相对极值的索引。

    使用这些索引将 index 直接放入与原始 DataFrame 形状相同的布尔数组中:

    import numpy as np
    import pandas as pd
    from scipy.signal import argrelextrema
    
    # for reproducibility 
    np.random.seed(42)
    
    # create toy DataFrame
    df = pd.DataFrame(data=np.random.random((100, 3)) * 20, columns=["AAPL", "MSFT", "TSLA"])
    
    # extract rows and cols indices using extrema
    rows, cols = argrelextrema(df.values, np.greater, axis=0,order=1)
    
    # create boolean numpy array
    values = np.zeros_like(df.values, dtype=bool)
    
    # set the values of the extrema to True
    values[rows, cols] = True
    
    # convert to DataFrame
    result = pd.DataFrame(data=values, columns=df.columns)
    print(result)
    

    输出

         AAPL   MSFT   TSLA
    0   False  False  False
    1   False  False   True
    2   False  False  False
    3   False   True   True
    4   False  False  False
    ..    ...    ...    ...
    95  False  False  False
    96   True  False   True
    97  False  False  False
    98   True   True   True
    99  False  False  False
    
    [100 rows x 3 columns]
    

    上面代码的重要部分是这样的:

    # create boolean numpy array
    values = np.zeros_like(df.values, dtype=bool)
    
    # set the values of the extrema to True
    values[rows, cols] = True
    

    作为替代方案,您可以直接从sparse.csr_matrix 构建values 数组:

    from scipy.sparse import csr_matrix
    values = csr_matrix((np.ones(rows.shape), (rows, cols)), shape=df.shape, dtype=bool).toarray()
    

    【讨论】:

    • 谢谢 - 事后看来,解决方案非常简单。谢谢你的解释
    猜你喜欢
    • 2018-06-06
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2015-05-19
    • 2017-08-06
    • 2021-01-06
    相关资源
    最近更新 更多