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
  • 1
  • 11

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
  • 317,841
  • 20
  • 164
  • 234
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
  • 26,119
  • 6
  • 18
  • 32
  • 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