Search code examples
pythonlistpandascomparison

Alternative to using np.where with list to yield a series instead of an ndarray to be more amenable to converting into a dataframe?


Is there an alternative to use np.where with a list so that I can work with a series instead of an ndarray?

animal = ['Buffalo', 'Gazelle']

df.one = np.where(df.one.isin(animal),'Herding Animal', df.one) 

Solution

  • df = pd.DataFrame({'one':['Buffalo','Gazelle','Leopard']})
    
    print(df)
           one
    0  Buffalo
    1  Gazelle
    2  Leopard
    
    animal = ['Buffalo', 'Gazelle']
    df.one.mask(df.one.isin(animal),'Herding Animal')
    print (df)
                  one
    0  Herding Animal
    1  Herding Animal
    2         Leopard
    
    df.to_frame()