Python 在 Pandas 中使用 ELIF 创建列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18194404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create Column with ELIF in Pandas
提问by DJElbow
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 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:
我无法弄清楚如何根据其他两列中的值创建新的 DataFrame 列。我需要使用 if/elif/else 逻辑。但是我发现的所有文档和示例都只显示了 if/else 逻辑。这是我正在尝试做的一个示例:
Code
代码
df['combo'] = 'mobile' if (df['mobile'] == 'mobile') elif (df['tablet'] =='tablet') 'tablet' else 'other')
I am open to using where() also. Just having trouble finding the right syntax.
我也愿意使用 where()。只是找不到正确的语法。
采纳答案by Viktor Kerkez
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.
如果您有多个分支语句,最好创建一个接受一行的函数,然后沿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)
回答by tbk
I tried the following and the result was much faster. Hope it's helpful for others.
我尝试了以下方法,结果要快得多。希望对其他人有帮助。
df['combo'] = 'other'
df.loc[df['mobile'] == 'mobile', 'combo'] = 'mobile'
df.loc[df['tablet'] == 'tablet', 'combo'] = 'tablet'
回答by ALollz
ELIF
logic can be implemented with np.select
or nested np.where
:
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'))
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
回答by Abhijeet Kelkar
Adding to np.where solution :
添加到 np.where 解决方案:
df['col1']= np.where(df['col'] < 3, 1,np.where( (df['col'] >3 )& (df['col'] <5),2,3))
Overall Logic is :
总体逻辑是:
np.where(Condition, 'true block','false block').
With each true/false block can in turn again be nested.
每个真/假块可以依次嵌套。
Also, Notice the &
for ANDing! (not 'and')
另外,请注意&
forANDing! (not 'and')