检查多行 pandas 中标志列的有效性 [英] check validity for flag column's in multiple rows pandas
问题描述
我有一个数据框:
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
数字.
i want to find the id
number where both flag1 and flag2 are 1
.
例如 对于id 1,在第一行中,标志1 = 1和标志2 = 0,在第二行中,标志1 = 0和标志2 = 1.
for eg. for id 1, in the first row, flag1 = 1 and flag2 = 0, and second row, flag1 = 0 and flag2 = 1.
我的最终输出应该是这样
my final output should look like this
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]
中使用
or only id column would also work [1,2,4]
in a list
由于id = 3,所以id = 3的两行的flag1均为1,flag 2的均为0,所以我不得不忽略它.
since for id = 3, flag1 was 1 in both the rows with id = 3 and flag 2 was 0, so i have to neglect it.
我试图写一个func,但是失败了.
i was trying to write a func, but failed.
def checkValidTransactionRow(frame):
df['id'][(df['flag1']==1) & (df['flag2']==1) ].unique()
推荐答案
尝试以下方法:
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.eq(1).any()
与(x == 1).any()
相同-即,如果x
系列中的至少一个值等于1
,则返回True
,否则返回False
x.eq(1).any()
is the same as (x == 1).any()
- i.e. return True
if at least one value in x
series equals to 1
, otherwise return False
更新:
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]
这篇关于检查多行 pandas 中标志列的有效性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!