The following is the dataframe
import pandas as pd
df = pd.DataFrame({'A' : [1, 1, 2, 2, 3, 4, 5],
'B' : [11, 11, 12, 12, 13,14,15],
'C' :[0.12232, 0.12232, 0.3455, 0.3455, 0.112, 0.567, 0.8901],
'D' :[False, True, True, True, True, True, True],
'E' :[True, True, False, True, True, True, True],
'F' :[False, True, False, True, True, True, True]})
A B C D E F
0 1 11 0.12232 False True False
1 1 11 0.12232 True True True
2 2 12 0.34550 True False False
3 2 12 0.34550 True True True
4 3 13 0.11200 True True True
5 4 14 0.56700 True True True
6 5 15 0.89010 True True True
using drop_duplicates with subset column list of dataframe does not work for me. please let me know, how to do this in a simple and fast way
If the values of columns A, B, C are duplicated. Please check if D, E, F are True, remove that row from the dataframe.
expected output dataframe:
A B C D E F
0 1 11 0.12232 False True False
2 2 12 0.34550 True False False
4 3 13 0.11200 True True True
5 4 14 0.56700 True True True
6 5 15 0.89010 True True True
We can use DataFrame.duplicated
to check A,B and C
+ DataFrame.all
to check D,E and F
. Series.mul
is used here to do the AND
operation between both boolean Series to make the code cleaner:
m =( df.duplicated(subset = ['A','B','C'],keep = False)
.mul(df[['D','E','F']].all(axis=1)) )
df.loc[~m]
Output
A B C D E F
0 1 11 0.12232 False True False
2 2 12 0.34550 True False False
4 3 13 0.11200 True True True
5 4 14 0.56700 True True True
6 5 15 0.89010 True True True
Here's my way:
t = (df['D'] == True) & (df['E'] == True) & (df['F'] == True) # check where D, E, F are True
e = df.duplicated(subset=['A','B', 'C']) # Check duplicates in A, B, C
a = (e == True) & (e == True) # Check where duplicates are true in D, E, F
a = a.index[a].tolist() # get the index
df = df.drop(index=a) # drop duplicates True in D, E, F
print(df)
# A B C D E F
# 0 1 11 0.12232 False True False
# 2 2 12 0.34550 True False False
# 4 3 13 0.11200 True True True
# 5 4 14 0.56700 True True True
# 6 5 15 0.89010 True True True
Consider using helper columns to subset logically by:
df = df.assign(grp_count = lamba x: x.groupby(['A','B','C']).transform('count'),
sum_bool = lamba x: x.reindex['D','E','F'].sum(axis=1))
sub_df = (df[(df['grp_count'] > 1 & df['sum_bool'] != 3) | (df['grp_count'] == 1)]
.drop(columns=['grp_count', 'sum_bool']))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.