首页 > 解决方案 > 根据数据框列的上一个和下一个元素创建一个 python 函数

问题描述

我有以下数据框:

       a         b      c     Label       Value
0  43.91 -0.041619  43.91         B       30.25
1  43.91 -0.041619  43.91         A       43.91
2  43.39  0.011913  43.91         B       43.91
3  45.56 -0.048801  43.91         B       30.52
4  45.43  0.002857  43.91         B       43.91
5  45.33  0.002204  43.91         A       43.91
6  45.68 -0.007692  43.91         A       22.21
7  46.37 -0.014992  43.91         B       43.91
...

我想要做的是为每一行创建一个执行如下操作的函数:

function =

if next element (+ 1) of column Value == column Value  AND previous element (- 1) of column Value != column Value AND column Value > 40 :

return True

else:
return False

然后基于此函数创建一个新列:

if df.Label = A:
  df[Value reached] = function

else:
  df[Value reached] = False

是否可以在 python 上实现这一点并实现类似以下输出?

       a         b      c     Label       Value   Value reached
0  43.91 -0.041619  43.91         B       30.25           False
1  43.91 -0.041619  43.91         A       43.91            True
2  43.39  0.011913  43.91         B       43.91           False
3  45.56 -0.048801  43.91         B       30.52           False
4  45.43  0.002857  43.91         B       43.91           False
5  45.33  0.002204  43.91         A       43.91           False
6  45.68 -0.007692  43.91         A       22.21           False
7  46.37 -0.014992  43.91         B       43.91           False
...

标签: pythonpandasdataframe

解决方案


国际大学联合会,Series.shift

df['Value reached'] = (df['Value'].ne(df['Value'].shift()) & 
                       df['Value'].eq(df['Value'].shift(-1)) & 
                       df['Label'].eq('A') &
                       df['Value'].gt(40))

print(df)

       a         b      c     Label       Value   Value reached
0  43.91 -0.041619  43.91         B       30.25           False
1  43.91 -0.041619  43.91         A       43.91            True
2  43.39  0.011913  43.91         B       43.91           False
3  45.56 -0.048801  43.91         B       30.52           False
4  45.43  0.002857  43.91         B       43.91           False
5  45.33  0.002204  43.91         A       43.91           False
6  45.68 -0.007692  43.91         A       22.21           False
7  46.37 -0.014992  43.91         B       43.91           False

推荐阅读