【问题标题】:How to apply argrelextrema function in Python 3.7?如何在 Python 3.7 中应用 argrelextrema 函数?
【发布时间】:2020-04-07 07:55:22
【问题描述】:

我正在尝试将 argrelextrema 函数与数据帧 df 一起应用。但无法正确申请。下面是我的代码

    import pandas as pd
    from scipy.signal import argrelextrema 
    np.random.seed(42)

        def maxloc(data):
            loc_opt_ind = argrelextrema(df.values, np.greater)
            loc_max = np.zeros(len(data))
            loc_max[loc_opt_ind] = 1
            data['loc_max'] = loc_max
            return data

        values = np.random.rand(23000)
        df = pd.DataFrame({'value': values})
        np.all(maxloc_faster(df).loc_max)

It gives me error 
that loc_max[loc_opt_ind] = 1
IndexError: too many indices for array 

【问题讨论】:

    标签: python python-3.x pandas numpy scipy


    【解决方案1】:

    Pandas 数据框是二维的。也就是说,df.values 是二维的,even 当它只有一列时。因此,loc_opt_ind 将包含 x 和 y 索引(两个元组;只需打印 loc_opt_ind 即可查看),不能用于索引 loc_max。您可能想使用df['values'].values(变成<Series>.values)或np.squeeze(df.values) 作为输入。请注意,argrelextrema 在这种情况下仍然返回一个元组,只是一个单元素,因此您可能需要 loc_opt_ind[0]np.where 具有类似的行为)。

    【讨论】:

    • 能否将df中的多个列作为一维来申请另一个函数?
    • 多列如何组合成一维的东西?
    • 我实际上想在 DataFrames 列表上应用这个 maxloc 函数,列表中的每个 dataFrame 都有多个列,但我只需要在 'value' 列上应用
    • 然后我们将df['value'] 作为argrelextrema 的输入:argrelextrema(df['value'], np.greater)
    • 我将它用作 loc_opt_ind =argrelextrema(np.squeeze(dataFrame_list['value'].values), np.greater) 但它给了我错误 TypeError: list indices must be integers or slices, not str
    猜你喜欢
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多