# 数据帧序列检测：查找连续三行具有负值的组

##### 问题描述投票：2回答：3

`-1, -2, -3, 2, -4, 3, -5, -4, -3, -7`

``````groups = my_grouping_function_by_sequence()
groups[0] = [-1,-2-3]
groups[1] = [-5,-4,-3,-7]
``````

python-3.x database pandas sequence series
##### 3个回答
3

``````grps = df['test'].gt(0).cumsum()
dfs = [d.dropna() for _, d in df.mask(df['test'].gt(0)).groupby(grps) if d.shape[0] >= 3]
``````

``````for df in dfs:
print(df)

test
0  -1.0
1  -2.0
2  -3.0
test
6  -5.0
7  -4.0
8  -3.0
9  -7.0
``````

``````print(grps)
0    0
1    0
2    0
3    1
4    1
5    2
6    2
7    2
8    2
9    2
Name: test, dtype: int32
``````

``````df.mask(df['test'].gt(0))
# same as df.mask(df['test'] > 0)

test
0  -1.0
1  -2.0
2  -3.0
3   NaN
4  -4.0
5   NaN
6  -5.0
7  -4.0
8  -3.0
9  -7.0
``````

``````for _, d in df.mask(df['test'].gt(0)).groupby(grps):
if d.shape[0] >= 3:
print(d.dropna())

test
0  -1.0
1  -2.0
2  -3.0
test
6  -5.0
7  -4.0
8  -3.0
9  -7.0
``````

0

@@ Erfan，您的回答非常出色，我仍在努力理解第二行。您的第一行使我开始尝试以我自己的效率较低的方式编写它。

``````import pandas as pd
df = pd.DataFrame({'test': [-1, -2, -3, 2, -4, 3, -5, -4, -3, -7]})
df['+ or -'] = df['test'].gt(0)
df['group'] = df['+ or -'].cumsum()

df_gb = df.groupby('group').count().reset_index().drop('+ or -', axis=1)

df_new = pd.merge(df, df_gb, how='left', on='group').drop('+ or -', axis=1)
df_new = df_new[(df_new['test_x'] < 0) & (df_new['test_y'] >=3)].drop('test_y',
axis=1)

for i in df_new['group'].unique():
j = pd.DataFrame(df_new.loc[df_new['group'] == i, 'test_x'])
print(j)
``````

0

``````df = pd.DataFrame({'test': [-1, -2, -3, 2, -4, 3, -5, -4, -3, -7]})
``````

``````df['j'] = np.where(df['test']<0,1,-1)
df['k']=df['j'].rolling(3, min_periods=1).sum()
df2=df[df['k']==3]
``````

slice 迭代地，数据帧在上方获得第3和2个连续行

``````for index, row in df2.iterrows():
print(df.loc[index - 2 : index + 0, 'test'])
``````