python - Output next row from criteria in Python DataFrame
问题描述
I am trying to find a way to get the next row in a Python DataFrame when the rows in another column is equal to something. In the below example I am looking to get the next row in column A when rows in column B says negative. The end result should be C in the last DataFrame. The output should be in another DataFrame format. How do I do that?
Test={'A':[1.5,2.3,3.5,4.4, 5.6, 7.8, 8.9], 'B':['Neg', 'Pos', 'Neg', 'Pos', 'Pos', 'Neg','Pos']}
Dataframe=pd.DataFrame(Test)
Dataframe
Test={'A':[1.5,2.3,3.5,4.4, 5.6, 7.8, 8.9], 'B':['Neg', 'Pos', 'Neg', 'Pos', 'Pos', 'Neg','Pos']}
Dataframe=pd.DataFrame(Test)
Dataframe
A B
0 1.5 Neg
1 2.3 Pos
2 3.5 Neg
3 4.4 Pos
4 5.6 Pos
5 7.8 Neg
6 8.9 Pos
C
0 2.3
1 4.4
2 8.9
解决方案
pandas.Series.shift
与 一起使用reset_index
:
df["A"].shift(-1)[df["B"].eq("Neg")].reset_index(drop=True)
输出:
0 2.3
1 4.4
2 8.9
Name: A, dtype: float64
推荐阅读
- php - Laravel 上的数据透视表有问题
- django - 如何修复“TypeError: post_details() got an unexpected keyword argument 'slug'”
- javascript - 在 Paypal 中,什么可以保护买家在结账时向他们的账户收取正确的金额?
- laravel - 带有 Javascript 的 Laravel Passport API
- pandas - 匹配查找导致错误 - 只能比较具有相同标签的系列对象
- c++ - MakeFile 未由 mingw32-make 执行
- r - 如何用R中的NA替换特定行和列中的某些值?
- php - 在没有打开 Telegram 应用程序的情况下向 Telegram Bot 发送消息
- php - 带有电子邮件重复检查的 PHP 订阅表单
- amazon-web-services - 如何在 s3 存储桶中更新对象时调用 lambda 自动触发的雅典娜?