I have a pandas dataframe with inconsistent rows. In the example below key1 and key2 are two values which put together must be unique, so the couple (key1 ,key2) is the primary key and should appear once in dataframe, while info is a binary information of (key1 ,key2) and could be T or F. Unfortunately (key1 ,key2) are repeated in the dataframe and sometimes they have info=T and other times info=F, which is obviously an error.
To remove repetitions I'd like to adopt this reasoning: I'd like to count how many times (for the same couple (key1 ,key2)) info is T and how many times info is F and
- if the frequencies are different (most of the time) keep
only one of the rows that have the most frequent value between
TandFwith a function likedf.drop_duplicates(subset = ["key1","key2"] , keep = "first")in whichfirstshould be the row with most frequent value ofinfo. - If instead 50% of
rows has
info=Tand 50% hasinfo=F, I want to remove all of them, because I have no idea which is the right one with a function likedf.drop_duplicates(subset = ["key1","key2"] , keep = False).
I don't know how to do this kind of filter because I want to keep 1 row if one case and 0 rows in the other, depending on the values of a specific column within groups of similar rows.
Desired behaviour
In:
key1 key2 info
0 a1 a2 T
1 a1 a2 T #duplicated row of index 0
2 a1 a2 F #similar row of indexes 0 and 1 but inconsistent with info field
3 b1 b2 T
4 b1 b2 T #duplicated row of index 3
5 b1 b3 T #not duplicated since key2 is different from indexes 3 and 4
6 c1 c2 T
7 c1 c2 F #duplicated row of index 5 but inconsistent with info field
Out:
key1 key2 info
0 a1 a2 T # for(a1,a2) T:2 and F:1
3 b1 b2 T # for(b1,b2) T:2 and F:0
5 b1 b3 T # for(b1,b3) T:1 and F:0
# no rows for (c1,c2) because T:1 and F:1
Thank you