问题
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.
回答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
回答2:
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'))
来源:https://stackoverflow.com/questions/61965890/pandas-dataframes-if-else-condition-on-multiple-columns