0

I have a Data frame as shown below

import pandas as pd

df = pd.DataFrame({
    "name": ["john","peter","john","alex"],
    "height": [6,5,4,4],
    "shape": ["null","null","null","null"]
})

I want to apply this--- If name == john and height == 6 return shape = good else if height == 4 return shape = bad else change the shape to middle so the final Dataframe should look like this

  df = ({
        "name": ["john","peter","john","alex"],
        "height": [6,5,4,4],
        "shape": ["good","middle","bad","bad"]
    })

The only library I want to use is 'Pandas' and I do NOT want to use 'lambda' or 'NumPy'. Thanks in advance for your time. I will upvote your answers.

OMID Davami
  • 69
  • 10

2 Answers2

1

Let us do np.select

import numpy as np

cond1=df.name.eq('john')&df.height.eq(6)
cond2=df.height.eq(4)
df['shape']=np.select([cond1,cond2],['good','bad'],'middle')
df
    name  height   shape
0   john       6    good
1  peter       5  middle
2   john       4     bad
3   alex       4     bad
BENY
  • 296,997
  • 19
  • 147
  • 204
1
np.where(if condition, yes,no). In this case I have nested the method. 

df.shape=np.where(df['height']==6,'good',np.where(df['height']==4, 'bad','middle'))

enter image description here

wwnde
  • 22,093
  • 5
  • 13
  • 27
  • Hi Thanks for the answer. Would you please add the condition? I said the condition is that if the Name== john and height == 6 but you only wrote one condition not both of them. @wwnde – OMID Davami May 23 '20 at 03:03