0

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?:

if a == 5:
  df['column name'] = 1
else:
  df['column name'] = 0
4
  • 1
    so your column is just a constant for every row? Commented Sep 12, 2022 at 14:27
  • yes it is really only one row but is replicated concatenated down stream Commented Sep 12, 2022 at 14:28
  • That (updating values one row at a time) doesn't sound like something you should do with a Pandas dataframe. You should calculate all the values, then do df['col_name'] = [value0, value1,...]. Commented Sep 12, 2022 at 14:31
  • it make sense in my use case and is a poc anyway. as i said this is only assigned to one row. Commented Sep 12, 2022 at 14:57

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.