Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add a new (binary) column in a dataframe, based on certain condition, for every group/id

I have the below dataframe:

#Load the required libraries
import pandas as pd

#Create dataset
data = {'id': [1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1,
               2, 2,2,2,2,
               3, 3, 3, 3, 3, 3,
               4, 4,4,4,4,4,4,4,
               5, 5, 5, 5, 5,5, 5, 5,5,],
        'cycle': [1,2, 3, 4, 5,6,7,8,9,10,11,
                  1,2, 3,4,5,
                  1,2, 3, 4, 5,6,
                  1,2,3,4,5,6,7,8,
                  1,2, 3, 4, 5,6,7,8,9,],
        'Salary': [5, 6, 7,8,9,6,4,12,5,14,15,
                   4, 5,6,7,8,
                   5,8,4,7,12,1,
                   8,1,2,7,4,5,8,1,
                   1, 4,9,10,11,7,13,4,15,],
        'Children': ['No', 'Yes', 'Yes', 'Yes', 'Yes', 'No','No', 'Yes', 'Yes', 'Yes', 'No',
                     'Yes', 'No', 'Yes', 'No', 'Yes',
                     'No','Yes', 'Yes', 'No','No', 'Yes',
                     'Yes','Yes', 'Yes', 'No','No', 'Yes', 'Yes', 'Yes',
                      'No',  'Yes', 'No', 'No', 'Yes', 'Yes', 'Yes', 'Yes', 'No',],
        'Days': [123, 128, 66, 66, 120, 141, 52,96, 120, 141, 52,
                 96, 120,128, 66, 120,
                 15,123, 128, 66, 120, 141,
                 141,128, 66, 123, 128, 66, 120,141, 
                 123, 128, 66, 123, 128, 66, 120, 141, 52,],
        }

#Convert to dataframe
df = pd.DataFrame(data)
print("df = \n", df)

The above dataframe looks as such:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Now, I need to add a binary column in this dataframe such that, in every group/id, whenever Salary >= 7, Binary value should be 1, else 0.

For, example, for id=1, the ‘Salary’ column is [5, 6, 7,8,9,6,4,12,5,14,15]. Hence, the Binary column should be [0, 0 , 1, 1, 0, 0 ,0 ,1 , 0 , 1 ,1]

The new dataframe looks as such:

enter image description here

Can somebody please let me know how do I achieve this task in Python?

>Solution :

One way is:

df['Binary']=0
df.loc[df['Salary']>=7,'Binary']=1

# another way:
df['Binary']=np.where(df['Salary'] >=7,1,0)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading