本文介绍了在 pandas 中使用ELIF创建列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

我在弄清楚如何根据其他两列中的值创建新的DataFrame列时遇到了麻烦.我需要使用if/elif/else逻辑.但是我发现的所有文档和示例仅显示了if/else逻辑.这是我正在尝试做的一个示例:

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 logic. But all of the documentation and examples I have found only show if/else logic. Here is a sample of what I am trying to do:

代码

df['combo'] = 'mobile' if (df['mobile'] == 'mobile') elif (df['tablet'] =='tablet') 'tablet' else 'other')

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

I am open to using where() also. Just having trouble finding the right syntax.

推荐答案

在具有多个分支语句的情况下,最好创建一个接受行的函数,然后将其沿axis=1应用.通常,这要比通过行迭代快得多.

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)

这篇关于在 pandas 中使用ELIF创建列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 18:16