Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dataframe boolean values with if statement

i wanna make if statement to show all REF_INT that are duplicated i tried this:

(df_picru['REF_INT'].value_counts()==1)

and it shows me all values with true or false but i dont wanna do something like this:

if (df_picru['REF_INT'].value_counts()==1)
print "df_picru['REF_INT']"
like image 680
amine bak Avatar asked Jul 24 '26 16:07

amine bak


2 Answers

In [28]: df_picru['new'] = \
             df_picru['REF_INT'].duplicated(keep=False) \
                     .map({True:'duplicates',False:'unique'})

In [29]: df_picru
Out[29]:
   REF_INT         new
0        1      unique
1        2  duplicates
2        3      unique
3        8  duplicates
4        8  duplicates
5        2  duplicates
like image 152
MaxU - stop WAR against UA Avatar answered Jul 27 '26 07:07

MaxU - stop WAR against UA


I think you need duplicated for boolean mask and for new column numpy.where:

mask = df_picru['REF_INT'].duplicated(keep=False)

Sample:

df_picru = pd.DataFrame({'REF_INT':[1,2,3,8,8,2]})

mask = df_picru['REF_INT'].duplicated(keep=False)
print (mask)
0    False
1     True
2    False
3     True
4     True
5     True
Name: REF_INT, dtype: bool

df_picru['new'] = np.where(mask, 'duplicates', 'unique')
print (df_picru)
   REF_INT         new
0        1      unique
1        2  duplicates
2        3      unique
3        8  duplicates
4        8  duplicates
5        2  duplicates

If need check at least one if unique value need any for convert boolean mask - array to scalar True or False:

if mask.any():
    print ('at least one unique')
at least one unique
like image 28
jezrael Avatar answered Jul 27 '26 06:07

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!