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

assign value to pandas column depending on variable

very simple one and despite several google searches I could not find an answer (somewhat Python newbie). I would like to assign either 1 or 0 to a panda data frame depending on some variable. here is the pseudo code:

variable = 5

df['column name'] = if variable == 5 then 1 else 0

any pointer very much welcome thanks.

this would work but feels a bit long wounded?:

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

if a == 5:
  df['column name'] = 1
else:
  df['column name'] = 0

>Solution :

You can directly convert the boolean to integer and assign it as the column value

df['column name'] = int(variable==5)

Above works for the specific case, but you can have conditional expression as well:

df['column name'] = X if variable == 5 else Y

where X is the value for True, and Y is value for False

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