与上一行比较和求和 [英] Comparison with the previous line and summation

查看:70
本文介绍了与上一行比较和求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据框中有一个表:

X1  X2
1   1
1   2
1   3
2   2
2   2
1   2

必须为每行计算值Y,如果X1 = X1(上一行),则el = 0,其中Y = X2(上一行)+1。结果:

It is necessary for each line calculate the value Y, where Y = X2(previous line)+1 if X1=X1(previous line), elso 0. Result:

X1  X2  Y
1   1   0
1   2   2
1   3   3
2   2   0
2   2   3
1   2   0


推荐答案

使用:

m = df['X1'].shift().eq(df['X1'])
df['Y'] = np.where(m, df['X2'].shift().add(1), 0).astype(int)
print (df)
   X1  X2  Y
0   1   1  0
1   1   2  2
2   1   3  3
3   2   2  0
4   2   2  3
5   1   2  0

详细信息

首先比较通过 Series.shift 系列获得。 eq 相等:

First compare by Series.shifted valeus by Series.eq for equality:

m = df['X1'].shift().eq(df['X1'])
print (m)
0    False
1     True
2     True
3    False
4     True
5    False
Name: X1, dtype: bool

然后移动列 X2 ,添加 1

print (df['X2'].shift().add(1))
0    NaN
1    2.0
2    3.0
3    4.0
4    3.0
5    3.0
Name: X2, dtype: float64

并设置新的 numpy.where

And set new column by numpy.where:

print (np.where(m, df['X2'].shift().add(1), 0))
[0. 2. 3. 0. 3. 0.]

@Divakar的另一种解决方案:

Another solution by @Divakar:

df['Y'] = df.X1.shift().eq(df.X1)*(df.X2+1).shift().fillna(0).astype(int)
#pandas 0.24+
#df['Y'] = df.X1.shift().eq(df.X1)*(df.X2+1).shift(fill_value=0)
print (df)
   X1  X2  Y
0   1   1  0
1   1   2  2
2   1   3  3
3   2   2  0
4   2   2  3
5   1   2  0

这篇关于与上一行比较和求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆