Python 检查多行中标志列的有效性

Python 检查多行中标志列的有效性,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据帧: a id flag1 flag2 abc 1 1 0 123 1 0 1 xyz 2 1 0 111 2 0 1 qwe 3 1 0 qwe 3 1 0 mmm 4 1 0 222 4 0 1 我想找到f

我有一个数据帧:

a      id   flag1    flag2
abc    1     1          0
123    1     0          1
xyz    2     1          0
111    2     0          1
qwe    3     1          0
qwe    3     1          0
mmm    4     1          0
222    4     0          1
我想找到flag1和flag2都是1的id号

例如。 对于id 1,第一行中的flag1=1和flag2=0,第二行中的flag1=0和flag2=1

我的最终输出应该是这样的

a    id    flag1   flag2
abc    1     1          0
123    1     0          1
xyz    2     1          0
111    2     0          1
mmm    4     1          0
222    4     0          1
或者只有id列在列表中也可以使用[1,2,4]

因为对于id=3,flag1在id=3的两行中都是1,flag2是0,所以我不得不忽略它

我试图写一个func,但失败了

def checkValidTransactionRow(frame):
df['id'][(df['flag1']==1) & (df['flag2']==1) ].unique()

我相信有更好的方法实现这一点,但您可以尝试:

df['count_max1'] = df.groupby(['id'])['flag1'].transform(max)
df['count_max2'] = df.groupby(['id'])['flag2'].transform(max)
# Select rows 
df[(df['count_max1'] ==1 & (df['count_max2'] == 1)]
变换矩阵的作用是:

a      id   flag1    flag2    count_max1   count_max2
abc    1     1          0         1            1
123    1     0          1         1            1
xyz    2     1          0         1            1
111    2     0          1         1            1
qwe    3     1          0         1            0
qwe    3     1          0         1            0
mmm    4     1          0         1            1
222    4     0          1         1            1
选择行时,最终输出将为:

a    id    flag1   flag2    count_max1  count_max2
abc    1     1          0       1            1
123    1     0          1       1            1
xyz    2     1          0       1            1
111    2     0          1       1            1
mmm    4     1          0       1            1
222    4     0          1       1            1 
稍后您可以删除count_max1和count_max2行,请尝试以下方法:

In [23]: ids = df.groupby('id')['flag1','flag2'].apply(lambda x: x.eq(1).any()).all(1)

In [24]: ids
Out[24]:
id
1     True
2     True
3    False
4     True
dtype: bool

In [25]: ids.index[ids]
Out[25]: Int64Index([1, 2, 4], dtype='int64', name='id')
说明:

In [26]: df.groupby('id')['flag1','flag2'].apply(lambda x: x.eq(1).any())
Out[26]:
   flag1  flag2
id
1   True   True
2   True   True
3   True  False
4   True   True
x、 eq1.any与x==1.any相同-即,如果x系列中至少有一个值等于1,则返回True,否则返回False

更新:


@jezrael你能看一看吗?在我看来,两种解决方案都很好,但似乎maxu解决方案更好。transformmax做什么?是的,但我不明白为什么对于行qwe count_max2是0,因为对于qwe@jezrael还有比这更好的解决方案吗?我得到的是TypeID作为系列,我能在唯一正确的地方得到ID吗?还有lambda x:x.eq1.的意思是什么?如果可能,你能用文字解释lambda x:x.eq1.的意思吗?我得到了正确的答案,但是我不理解代码当我运行这段代码时,它工作得很好,但是当我在一个大型python程序中使用这部分代码时,它给了我错误异常
In [34]: ids.index[ids].values
Out[34]: array([1, 2, 4], dtype=int64)

In [35]: ids.index[ids].values.tolist()
Out[35]: [1, 2, 4]