python - 如何根据上一行和下一行的条件在 Pandas Dataframe 上创建新列?

标签 python python-3.x pandas dataframe conditional-statements

我正在尝试创建一个新的 Pandas 列,指示一个数字与上面的行和下面的行相比是否是最大的。

该列将是二进制的,其中“1”表示它是与上一行和下一行相比的最高数字,“0”表示不满足条件。

数据如下:

           Date      High
    0   2015-11-11  25.90
    1   2015-11-12  27.12
    2   2015-11-13  26.20
    3   2015-11-16  26.19
    4   2015-11-17  25.51
    5   2015-11-18  26.31
    6   2015-11-19  26.00
    7   2015-11-20  27.01
    8   2015-11-23  25.60
    9   2015-11-24  27.00
    10  2015-11-25  26.49

这是我想要的结果:

    Date        High    higher
0   2015-11-11  25.90   0.0
1   2015-11-12  27.12   1.0
2   2015-11-13  26.20   0.0
3   2015-11-16  26.19   0.0
4   2015-11-17  25.51   0.0
5   2015-11-18  26.31   1.0
6   2015-11-19  26.00   0.0
7   2015-11-20  27.01   1.0
8   2015-11-23  25.60   0.0
9   2015-11-24  27.00   1.0
10  2015-11-25  26.49   0.0

为了进一步说明,以下是我在 Microsoft Excel 上所做的操作,这正是我试图使用 Python 实现的目标: ExcelExample

第一次尝试:

for i in dftest['High']:
    if dftest['High'][i] > dftest['High'][i-1] and dftest['High'][i] > dftest['High'][i+1]:
        dftest['higher'] = 1
    else:
        dftest['higher'] = 0

这会导致错误: “TypeError:无法使用“float”类的这些索引器 [25.9] 对“pandas.core.indexes.range.RangeIndex”类进行标签索引”

第二次尝试: 这里我尝试使用'.shift()'。

for i in dftest['High']:
    if dftest['High'] > dftest['High'].shift(1) and dftest['High'] > dftest['High'].shift(-1):
        dftest['higher'] = 1
    else:
        dftest['higher'] = 0

这会导致错误: “类型错误:& 不支持的操作数类型:'float' 和 'float'”

第三次尝试(与第二次尝试类似): 使用“&”运算符代替“and”。

结果错误: “TypeError:无法使用“float”类的这些索引器 [25.9] 对“pandas.core.indexes.range.RangeIndex”类进行标签索引”

非常感谢任何形式的帮助!

编辑:如果我想找到 5 个或 7 个或 9 个连续数字中最大的一个,如果所提供的解决方案可以轻松替换,我将非常感激。再次感谢您!

最佳答案

这就是所谓的局部最大值

from scipy.signal import argrelextrema
ary=argrelextrema(df.High.values,np.greater)
df['local max']=np.where(df.index.isin(ary[0]),1,0)
df
          Date   High  local max
0   2015-11-11  25.90          0
1   2015-11-12  27.12          1
2   2015-11-13  26.20          0
3   2015-11-16  26.19          0
4   2015-11-17  25.51          0
5   2015-11-18  26.31          1
6   2015-11-19  26.00          0
7   2015-11-20  27.01          1
8   2015-11-23  25.60          0
9   2015-11-24  27.00          1
10  2015-11-25  26.49          0

关于python - 如何根据上一行和下一行的条件在 Pandas Dataframe 上创建新列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61880683/

相关文章:

python - 如何按名称选择不相邻的多个列并结合几种切片方法?

javascript - 谷歌浏览器扩展 :Call Python function from javascript

python - 在损失函数中结合交叉熵和均方误差

python - 为什么 Perl 和 Python 的 "\n"打印输出不同?

python - 按列值扩展数据框

python-3.x - 返回所有 NaN 的 Python- ARIMA 预测

javascript - 如何通过 Javascript 在 PythonAnywhere 上的 OpenCV 中访问网络摄像头?

python - 如何处理 python 中与 sys.argv[] 相关的错误?

python - Pandas .str.replace 和不区分大小写

python - 没有迭代的两个数据帧的交集