比较 Pandas 列中的上一个和下一个不同值

我有一个带有一列浮点数的数据框,看起来像这样(为简单起见,示例使用整数):


  col1                    

0 10    

1 10  

2 5

3 5

4 5

5 10

6 4

7 4

8 4

9 4

10 4

11 5

12 5

我正在尝试创建一个新列,为每一行比较该行中的前一个和下一个不同值,并根据它们是否相等分配一个布尔值。例如,在 row[2] 中,值为 5,在 row[1] 中,前一个不同值(不是 5)是 10,在 row[5] 中,下一个不同值是 10。在这种情况下,新列中的值为True。


然后,例如 df 我试图获得的输出是


  col1  col2                

0 10    NaN

1 10    False

2 5     True

3 5     True

4 5     True

5 10    False

6 4     False

7 4     False

8 4     False

9 4     False

10 4    False

11 5    False

12 5    NaN

我知道如何与特定数量的前后行进行比较,但我不知道是否可以通过搜索“第一个不同的值”进行比较。


有什么办法吗?


非常感谢!


守候你守候我
浏览 147回答 1
1回答

肥皂起泡泡

您可以连续使用唯一值来完成它,然后reindex喜欢:s = df['col1'] #to ease the code#where the value is not the same as beforem = s.diff().ne(0) # unique value if followingsu = 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 valuedf['col1_after'] = su.reindex(m.cumsum().values).valuesdf['col1_before'] = su.reindex(m.cumsum().values-2).values#create col2 where the two previous columns are equaldf['col2'] = df['col1_after'].eq(df['col1_before'])你得到print (df)    col1  col1_after  col1_before   col20     10         5.0          NaN  False1     10         5.0          NaN  False2      5        10.0         10.0   True3      5        10.0         10.0   True4      5        10.0         10.0   True5     10         4.0          5.0  False6      4         5.0         10.0  False7      4         5.0         10.0  False8      4         5.0         10.0  False9      4         5.0         10.0  False10     4         5.0         10.0  False11     5         NaN          4.0  False12     5         NaN          4.0  False请注意,您可以df.drop(['col1_after','col1_before'], axis=1)删除不需要的列,我将它们留在这里以显示正在发生的事情
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python