Create Column with ELIF in Pandas

前端 未结 4 921
轻奢々
轻奢々 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:29

    In cases where you have multiple branching statements it's best to create a function that accepts a row and then apply it along the axis=1. This is usually much faster then iteration through rows.

    def func(row):
        if row['mobile'] == 'mobile':
            return 'mobile'
        elif row['tablet'] =='tablet':
            return 'tablet' 
        else:
            return 'other'
    
    df['combo'] = df.apply(func, axis=1)
    

提交回复
热议问题