我有一个数据框
Day Value
1 Mon 0
2 Mon 1
3 Fri 1
4 Mon 1
5 Mon 1
6 Mon 1
7 Mon 0
8 Tue 1
9 Tue 1
我想通过与日列分组来找到具有两个连续 1 的行。
预期输出:
Day Value
5 Mon 1
6 Mon 1
9 Tue 1
最佳答案
使用boolean indexing
用于过滤:
m = df['Value'].eq(1)
s = df['Day'].ne(df['Day'].shift()).cumsum()
df = df[s[m].duplicated() & m]
print (df)
Day Value
5 Mon 1
6 Mon 1
9 Tue 1
详细信息:
首先使用 Series.shift
创建连续系列和 Series.ne
和 Series.cumsum
:
print (df['Day'].ne(df['Day'].shift()).cumsum())
1 1
2 1
3 2
4 3
5 3
6 3
7 3
8 4
9 4
Name: Day, dtype: int32
然后按 Value
中的 1
值进行过滤:
print (s[m])
2 1
3 2
4 3
5 3
6 3
8 4
9 4
Name: Day, dtype: int32
并获取Series.duplicated
对于所有名为 s
的助手 Series
的欺骗:
print (s[m].duplicated())
2 False
3 False
4 False
5 True
6 True
8 False
9 True
Name: Day, dtype: bool
最后一个链通过 &
进行按位与,以获得与原始大小相同的掩码:
print (s[m].duplicated() & m)
1 False
2 False
3 False
4 False
5 True
6 True
7 False
8 False
9 True
dtype: bool
关于python - 如何在Python中比较两行并通过索引获取结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61039990/