Create Column with ELIF in Pandas

前端 未结 4 955
轻奢々
轻奢々 2020-11-29 01:50

Question

I am having trouble figuring out how to create new DataFrame column based on the values in two other columns. I need to use if/elif/else l

4条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 02:14

    ELIF logic can be implemented with np.select or nested np.where:

    import numpy as np
    
    df['combo'] = np.select([df.mobile == 'mobile', df.tablet == 'tablet'], 
                            ['mobile', 'tablet'], 
                            default='other')
    # or 
    df['combo'] = np.where(df.mobile == 'mobile', 'mobile', 
                           np.where(df.tablet == 'tablet', 'tablet', 'other'))
    

    Sample Data + Output:

       mobile  tablet   combo
    0  mobile     bar  mobile
    1     foo  tablet  tablet
    2     foo     nan   other
    3  mobile  tablet  mobile
    4  mobile     nan  mobile
    5     foo  tablet  tablet
    6  mobile     bar  mobile
    7  mobile  tablet  mobile
    8  mobile     bar  mobile
    9  mobile     nan  mobile
    

提交回复
热议问题