Pandas finding local max and min

后端 未结 3 1357
我在风中等你
我在风中等你 2020-12-04 11:43

I have a pandas data frame with two columns one is temperature the other is time.

I would like to make third and fourth columns called min and max. Each of these co

3条回答
  •  悲哀的现实
    2020-12-04 11:57

    Assuming that the column of interest is labelled data, one solution would be

    df['min'] = df.data[(df.data.shift(1) > df.data) & (df.data.shift(-1) > df.data)]
    df['max'] = df.data[(df.data.shift(1) < df.data) & (df.data.shift(-1) < df.data)]
    

    For example:

    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    
    # Generate a noisy AR(1) sample
    np.random.seed(0)
    rs = np.random.randn(200)
    xs = [0]
    for r in rs:
        xs.append(xs[-1]*0.9 + r)
    df = pd.DataFrame(xs, columns=['data'])
    
    # Find local peaks
    df['min'] = df.data[(df.data.shift(1) > df.data) & (df.data.shift(-1) > df.data)]
    df['max'] = df.data[(df.data.shift(1) < df.data) & (df.data.shift(-1) < df.data)]
    
    # Plot results
    plt.scatter(df.index, df['min'], c='r')
    plt.scatter(df.index, df['max'], c='g')
    df.data.plot()
    

提交回复
热议问题