【问题标题】:Pandas DataFrames If else condition on multiple columns [duplicate]Pandas DataFrames If else 条件多列[重复]
【发布时间】:2020-09-09 22:27:27
【问题描述】:

我有一个如下图所示的数据框

import pandas as pd

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

我想应用这个--- 如果 name == john and height == 6 return shape = good else if height == 4 return shape = bad else 将形状更改为中间 所以最终的 Dataframe 应该是这样的

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

我想使用的唯一库是“Pandas”,我不想使用“lambda”或“NumPy”。 在此先感谢您的时间。 我会赞成你的答案。

【问题讨论】:

    标签: python pandas dataframe if-statement conditional-statements


    【解决方案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'))
    

    【讨论】:

    • 您好,感谢您的回答。请加条件好吗?我说条件是如果 Name== john 和 height == 6 但你只写了一个条件而不是两个条件。 @wwnde
    【解决方案2】:

    让我们做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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-01
      • 2019-12-15
      • 1970-01-01
      • 2019-03-27
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      • 2019-12-28
      相关资源
      最近更新 更多