Pandas DataFrames If else condition on multiple columns [duplicate]

核能气质少年 提交于 2021-01-29 07:36:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!