Python 3.x 数据帧序列检测:查找一行中三行为负值的组
假设我有一个列Python 3.x 数据帧序列检测:查找一行中三行为负值的组,python-3.x,database,pandas,sequence,series,Python 3.x,Database,Pandas,Sequence,Series,假设我有一个列df['test']: -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] 熊猫数值数据中的序列测试是否有一些预定义的检查?它不需要是熊猫,但我正在寻找一个快速和适应性强的解决方案。任何建议都会有帮助。谢谢 使用GroupBy和cumsum创建连续
df['test']
:
-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]
熊猫数值数据中的序列测试是否有一些预定义的检查?它不需要是熊猫,但我正在寻找一个快速和适应性强的解决方案。任何建议都会有帮助。谢谢 使用
GroupBy
和cumsum
创建连续负数组
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
但是,正如我们所看到的,它也包括正数,我们不想在输出中考虑。因此,我们使用DataFrame.mask
将这些值转换为NaN
:
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
然后我们在此数据帧上分组,只保留=
3行的组:
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
@你的回答很好,我还在努力理解第二句话。你的第一句话让我开始尝试用我自己的,效率较低的方式来写
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)
将熊猫作为pd导入
数据帧({'test':[-1,-2,-3,2,-4,3,-5,-4,-3,-7]})
df['+或-']=df['test'].gt(0)
df['group']=df['+或-'].cumsum()
df_gb=df.groupby('group').count().reset_index().drop('+或-',axis=1)
df_new=pd.merge(df,df_gb,how='left',on='group').drop('+或-',axis=1)
df_new=df_new[(df_new['test_x']<0)和(df_new['test_y']>=3)]。下降('test_y',
轴=1)
对于df_new['group']中的i.unique():
j=pd.DataFrame(df_new.loc[df_new['group']==i,‘test_x']))
印刷品(j)
也承认@erfan回答优雅但不容易理解。下面是我的尝试
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]
我个人也喜欢这种方法,并最终在我的代码中使用了这种方法,因为它易于阅读。谢谢
for index, row in df2.iterrows():
print(df.loc[index - 2 : index + 0, 'test'])