Python pandas - 根据前一行值

时间:2018-06-11 15:55:43

标签: python pandas

我有一个大数据集,我试图只过滤符合特定条件的行。更具体地说,我希望得到Type == A if Type == B is 2

的所有行

因此,在下面的示例中,它将导致行2 Node-1 A 1

>>> import pandas as pd
>>> data = [['Node-0', 'A', 1],['Node-0', 'B', 1],['Node-1','A', 1],['Node-1', 'B', 2]]
>>> df = pd.DataFrame(data,columns=['Node','Type','Value'])
>>> print df
     Node Type  Value
0  Node-0    A     1
1  Node-0    B     1
2  Node-1    A     1
3  Node-1    B     2

我可以使用df.loc[df['Type'] == 'A']过滤行,但这会为我提供行02

3 个答案:

答案 0 :(得分:1)

IIUC,使用groupby进行一些掩蔽。

m = df.Type.eq('B') & df.Value.eq(2)
df[m.groupby(df.Node).transform('any') & df.Type.eq('A')]

     Node Type  Value
2  Node-1    A      1

答案 1 :(得分:0)

我打赌有一个更好的解决方案,但这应该暂时解决:

condition1 = (df['Node'].isin(df.query("Type=='B' & Value==2")['Node']))
#All the 'Node' values whose 'Type' and 'Value' columns have values 'B' and 2
#.isin() filters to rows that match the above criteria

condition2 = (df['Type']=='A')
#all the rows where 'Type' is 'A'

df.loc[condition1&condition2]
#intersection of above conditions    

#     Node Type  Value
#2  Node-1    A      1

答案 2 :(得分:0)

请考虑以下事项:

# Get rows maching first criteria
dd1 = df[df.Type == 'A'][df.Value == 1]

# Get "previous" rows maching second criteria
df2 = df.shift(-1)
dd2 = df2[df2.Type == 'B'][df2.Value == 2]

# Find intersection
pd.merge(dd1, dd2, how='inner', on='Node')

结果:

     Node Type_x  Value_x Type_y  Value_y
0  Node-1      A        1      B      2.0
相关问题