[英]Using the apply function in combination with the shift function
I'm trying to iterate thru a dataframe. 我正在尝试通过数据框进行迭代。 My goal would be to increase the value in the column
loop
when in the column rpm
the previous row and the actual row aren't equal. 我的目标是在列
rpm
中前一行与实际行不相等时增加列loop
的值。
df = pd.DataFrame({'rpm': [5000, 5000, 10000, 10000, 15000, 15000],
'temp': [23, 23, 24, 23, 24, 25]})
df['loop'] = 0
def loop_no(x,y):
if x.rpm != y.rpm:
val = y.loop + 1
else:
val = x.loop
return val
df['loop'] = df.apply(lambda x: loop_no(x, x.shift(-1)))
At this point, I get this error: 在这一点上,我得到这个错误:
AttributeError: ("'Series' object has no attribute 'rpm'", u'occurred at index rpm').
When I use axis=1
, I don't get an error. 当我使用
axis=1
,不会出现错误。 But obviously it shifts then in column direction. 但是很明显,它然后向列方向移动。 So, I don't get the previous line.
所以,我没有得到前一行。
df['loop'] = df.apply(lambda x: loop_no(x, x.shift(-1)), axis=1)
IIUC IIUC
(df.rpm!=df.rpm.shift(-1)).cumsum()
Out[796]:
0 0
1 1
2 1
3 2
4 2
5 3
Name: rpm, dtype: int32
More info 更多信息
df['loop']=(df.rpm!=df.rpm.shift(-1)).cumsum()
df
Out[799]:
rpm temp loop
0 5000 23 0
1 5000 23 1
2 10000 24 1
3 10000 23 2
4 15000 24 2
5 15000 25 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.