0

So basically I am trying to write a statement where if a value in Col1 = 1 or Col2 = 1 than create a new column with the value 10 and if both Col1 and Col2 = 0 the new column should print 0 or just skip.

so far this is what I did

if df.Col1 == 1 or df.Col2 == 1:
    df['newCol'] = 10
else: pass

This is giving me an error.

BigBen
  • 46,229
  • 7
  • 24
  • 40
  • Does this answer your question? [Pandas/Python: Set value of one column based on value in another column](https://stackoverflow.com/questions/49161120/pandas-python-set-value-of-one-column-based-on-value-in-another-column) – JNevill Nov 04 '21 at 14:58
  • the thing is this is based on one parameter. I want to make an statement that satisfy both parameters – Saad Farooqui Nov 04 '21 at 15:05
  • It's the same syntax you just use an `OR` operator (`|`) in your condition (the first parameter in the `where` method. The real take-away is that anytime you are in a dataframe and you think "I need to loop" it should throw red flags. – JNevill Nov 04 '21 at 15:19

2 Answers2

0

You can do this:

df['newCol'] = np.where(((df['Col1']==1)|(df['Col2']==1)), 10,np.nan)
0

Try this assuming df is your dataframe.. df['newcolumn'] =df.apply(function, axis=1) then in function write def function(row) : if row['col1'] == 1 or row['Col2'] == 1: return 10 (you can pass 0 in else part as well)