[英]How to check if next 3 consecutive rows in pandas column have same value?
I have a pandas dataframe with 3 columns - id
, date
and value
.我有一个 pandas dataframe 有 3 列 -
id
, date
和value
。
| id | date | value |
| --- | --- | --- |
| 1001 | 1-04-2021 | 61 |
| 1001 | 3-04-2021 | 61 |
| 1001 | 10-04-2021 | 61 |
| 1002 | 11-04-2021 | 13 |
| 1002 | 12-04-2021 | 12 |
| 1015 | 18-04-2021 | 42 |
| 1015 | 20-04-2021 | 42 |
| 1015 | 21-04-2021 | 43 |
| 2001 | 8-04-2021 | 27 |
| 2001 | 11-04-2021 | 27 |
| 2001 | 12-04-2021 | 27 |
| 2001 | 27-04-2021 | 27 |
| 2001 | 29-04-2021 | 27 |
I want to check how many rows are there for each id
where the next 3 or more than 3 next consecutive rows having the same value in value
column?我想检查每个
id
有多少行,其中下一个 3 或 3 个以上的连续行在value
列中具有相同的值? Once identified that the next 3 or more consecutive rows are having the same value, flag them as 1 in a separate column else 0.一旦确定接下来的 3 个或更多连续行具有相同的值,则在单独的列中将它们标记为 1,否则标记为 0。
So the final dataframe would look like the following,所以最终的 dataframe 如下所示,
| id | date | value | pattern
| --- | --- | --- | --- |
| 1001 | 1-04-2021 | 61 | 1 |
| 1001 | 3-04-2021 | 61 | 1 |
| 1001 | 10-04-2021 | 61 | 1 |
| 1002 | 11-04-2021 | 13 | 0 |
| 1002 | 12-04-2021 | 12 | 0 |
| 1015 | 18-04-2021 | 42 | 0 |
| 1015 | 20-04-2021 | 42 | 0 |
| 1015 | 21-04-2021 | 43 | 0 |
| 2001 | 8-04-2021 | 27 | 1 |
| 2001 | 11-04-2021 | 27 | 1 |
| 2001 | 12-04-2021 | 27 | 1 |
| 2001 | 27-04-2021 | 27 | 1 |
| 2001 | 29-04-2021 | 27 | 1 |
Try with groupby
:尝试使用
groupby
:
df['pattern'] = (df.groupby(['id', df['value'].diff().ne(0).cumsum()])
['id'].transform('size').ge(3).astype(int)
)
How about this:这个怎么样:
def f(x):
x = x.fillna(0)
y = len(x)*[0]
for i in range(len(x)-3):
if x[i+1] == 0 and x[i+2] == 0:
y[i] = 1
y[i+1] = 1
y[i+2] = 1
if x[len(x)-1] == 0 and x[len(x)-2] == 0 and x[len(x)-3] == 0:
y[len(x)-1] = 1
return pd.Series(y)
df['value'].diff().transform(f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.