Search code examples
pythondataframeif-statementconditional-statementsseries

Conditions on a DF or Series.?


Hi I imported a dataset called train and selected "Sex" from this list.

But I couldn't use the if statement on it. I get the following error :

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

I have already tried changing it to string datatype but without result.

What can i do to fix this? Changing it to a DF doesnt help same error.

import numpy as np



Sex = train['Sex']


for x in Sex : 
    if Sex == "male" :
        SurvBi = 0
    else :
        SurBi = 1

Solution

  • this solution may help

    import pandas as pd
    
    train = {
      "Sex": ["male","female"],
    }
    Sex = train['Sex']
    for x in Sex:
    
        SurvBi = 0 if x == "male" else 1
        print(SurvBi)