在Pandas中使用ELIF创建列

DJE*_*bow 16 python pandas

我无法根据其他两列中的值来确定如何创建新的DataFrame列.我需要使用if/elif/else逻辑.但我发现的所有文档和示例只显示if/else逻辑.这是我想要做的一个示例:

df['combo'] = 'mobile' if (df['mobile'] == 'mobile') elif (df['tablet'] =='tablet') 'tablet' else 'other')
Run Code Online (Sandbox Code Playgroud)

我也愿意使用where().只是找不到合适的语法.

tbk*_*tbk 36

我尝试了以下内容,结果更快.希望它对其他人有帮助.

df['combo'] = 'other'
df.loc[df['mobile'] == 'mobile', 'combo'] = 'mobile'
df.loc[df['tablet'] == 'tablet', 'combo'] = 'tablet'
Run Code Online (Sandbox Code Playgroud)

  • 这是熊猫食谱中推荐的方法.http://pandas.pydata.org/pandas-docs/stable/cookbook.html#idioms (2认同)

Vik*_*kez 28

如果您有多个分支语句,最好创建一个接受行的函数,然后沿着它应用它axis=1.这通常比遍历行迭快得多.

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)
Run Code Online (Sandbox Code Playgroud)


ALo*_*llz 7

ELIF逻辑可以实现np.select或嵌套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'))
Run Code Online (Sandbox Code Playgroud)

样本数据+输出:

   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
Run Code Online (Sandbox Code Playgroud)

  • 这确实应该是公认的解决方案;它是可扩展的,甚至不需要额外的导入:“pd.np.select”。 (5认同)