pandas 根据不同列中的先前值取值 [英] Pandas taking value based on previous value in a different column
本文介绍了 pandas 根据不同列中的先前值取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这可能很简单,但由于某种原因,我想不出解决它的好方法.
It may be simple, but for some reason I can't think of a good way to solve it.
所以,假设这是我的 DataFrame:
So, let's say this is my DataFrame:
a b
0 99 3
1 99 56
2 1 7
3 1 80
4 1 55
5 2 601
6 2 -4
7 1 33
8 1 22
我想创建一个新列 c
,其中的值将是 a
前一个值中 b
的最后一个值>,所以输出应该是:
I would like to create a new column, c
, where the values will be the last value of b
in the previous value of a
, so the output should be:
a b c
0 99 3 nan
1 99 56 nan
2 1 7 56
3 1 80 56
4 1 55 56
5 2 601 55
6 2 -4 55
7 1 33 -4
8 1 22 -4
任何帮助将不胜感激!
推荐答案
我会将 df['a']
与其位移进行比较以识别值的变化,以及 ffill()
和 shift()
:
I would compare df['a']
to its shift to identify value changes, and ffill()
with shift()
:
df['c'] = df.loc[df['a'] != df['a'].shift(-1),'b']
df['c'] = df['c'].ffill().shift()
输出:
a b c
0 99 3 NaN
1 99 56 NaN
2 1 7 56.0
3 1 80 56.0
4 1 55 56.0
5 2 601 55.0
6 2 -4 55.0
7 1 33 -4.0
8 1 22 -4.0
这篇关于 pandas 根据不同列中的先前值取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文