1 回答

TA贡献1829条经验 获得超6个赞
您可以连续使用唯一值来完成它,然后reindex喜欢:
s = df['col1'] #to ease the code
#where the value is not the same as before
m = s.diff().ne(0)
# unique value if following
su = s[m].reset_index(drop=True)
print (su)
# 0 10
# 1 5
# 2 10
# 3 4
# 4 5
# Name: col1, dtype: int64
#create columns in df to align previous and after not equal value
df['col1_after'] = su.reindex(m.cumsum().values).values
df['col1_before'] = su.reindex(m.cumsum().values-2).values
#create col2 where the two previous columns are equal
df['col2'] = df['col1_after'].eq(df['col1_before'])
你得到
print (df)
col1 col1_after col1_before col2
0 10 5.0 NaN False
1 10 5.0 NaN False
2 5 10.0 10.0 True
3 5 10.0 10.0 True
4 5 10.0 10.0 True
5 10 4.0 5.0 False
6 4 5.0 10.0 False
7 4 5.0 10.0 False
8 4 5.0 10.0 False
9 4 5.0 10.0 False
10 4 5.0 10.0 False
11 5 NaN 4.0 False
12 5 NaN 4.0 False
请注意,您可以df.drop(['col1_after','col1_before'], axis=1)删除不需要的列,我将它们留在这里以显示正在发生的事情
添加回答
举报