pandas - python if statement returns value error -


i'm sorry ask apparently simple question, python beginner , couln't find answer anywhere. want run simple if statement, python returns just:

    valueerror: truth value of series ambiguous. use a.empty, a.bool(), a.item(), a.any() or a.all().  

no matter of given alternatives apply - doesn't work. have ideas?

    import pandas pd      df = pd.dataframe({'a': [none] * 4, 'b': [2, 3, 10, 3]})      df["c"] =0         if df.b == 2:         df.c =1 

you can't compare scalar array using if becomes ambiguous if 1 of values matches or 1 want like:

in [3]:  df['c'] = np.where(df['b'] == 2, 1, np.nan) df out[3]:         b   c 0  none   2   1 1  none   3 nan 2  none  10 nan 3  none   3 nan 

using np.where looks @ whole array condition , if true returns 1, otherwise nan

you can perform comparisons using syntax like:

in [4]:  df['b'] == 2 out[4]: 0     true 1    false 2    false 3    false name: b, dtype: bool 

but not using if unless comparing single value:

in [8]:  index, row in df.iterrows():     if row['b'] == 2:         print('equals 2')     else:         print('some other value') equals 2 other value other value other value 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -