pandas 找到当地的最大值和最小值 [英] Pandas finding local max and min

查看:78
本文介绍了 pandas 找到当地的最大值和最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框,其中有两列,一列是温度,另一列是时间.

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

我想在第三和第四列中分别命名为最小值"和最大值".除了存在局部最小值或最大值的地方,这些列中的每一列都将用nan填充,然后它将具有该极值.

I would like to make third and fourth columns called min and max. Each of these columns would be filled with nan's except where there is a local min or max, then it would have the value of that extrema.

这里是数据看起来的样本,本质上,我试图确定图中的所有峰值和低点.

Here is a sample of what the data looks like, essentially I am trying to identify all the peaks and low points in the figure.

有没有内置的熊猫工具可以做到这一点?

Are there any built in tools with pandas that can accomplish this?

推荐答案

假定感兴趣的列标记为data,则一种解决方案是

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)]

例如:

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()

这篇关于 pandas 找到当地的最大值和最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆