python - 根据数据框列的上一个和下一个元素创建一个 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
...
解决方案
国际大学联合会,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
推荐阅读
- dictionary - Boost.Container flat_map 和 std::string_view
- android - Looper 线程问题?但不使用动画师
- php - 如何使用 HttpRequest.php 到 Laravel
- c# - 无法将跟踪事件记录到 Application Insights
- php - 五个独特的页面导致一页。我可以更改
- swift - UserDefaults.standard.set(any, forKey:) 写字典 SIGABRTs 时?
- linux - perf:为什么我没有“系统调用”计数器?
- javascript - 如何在 React 组件上放置未平面化的 svg 文件
- sparql - 如何使用 SPARQL 从 dbpedia 获取 'is dct:subject of' 属性
- django - 在 django admin 中更改显示顺序(数字)更容易?