在 Pandas 中使用 ELIF 创建列
- 2025-03-21 09:06:00
- admin 原创
- 32
问题描述:
问题
我无法弄清楚如何根据其他两列中的值创建新的 DataFrame 列。我需要使用 if/elif/else 逻辑。但我发现的所有文档和示例都只显示 if/else 逻辑。以下是我正在尝试执行的操作的示例:
代码
df['combo'] = 'mobile' if (df['mobile'] == 'mobile') elif (df['tablet'] =='tablet') 'tablet' else 'other')
我也愿意使用 where()。只是找不到正确的语法。
解决方案 1:
如果您有多个分支语句,最好创建一个接受一行然后沿其应用的函数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)
解决方案 2:
我尝试了以下方法,结果更快。希望对其他人有帮助。
df['combo'] = 'other'
df.loc[df['mobile'] == 'mobile', 'combo'] = 'mobile'
df.loc[df['tablet'] == 'tablet', 'combo'] = 'tablet'
解决方案 3:
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'))
样本数据+输出:
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
解决方案 4:
添加到 np.where 解决方案:
df['col1']= np.where(df['col'] < 3, 1,np.where( (df['col'] >3 )& (df['col'] <5),2,3))
总体逻辑是:
np.where(Condition, 'true block','false block').
每个真/假块可以依次再次嵌套。
另外,请&
注意ANDing! (not 'and')
解决方案 5:
添加应用 lambda 解决方案:
df['combo'] = df.apply(lambda x: 'mobile' if x['mobile'] == 'mobile' else \n ('tablet' if x[''mobile']== 'tablet' else 'other'), axis=1)
结构 :
df['column_name'] = df.apply(lambda x: 'value if true 1' if x['column_name_check_1'] == 'condition_1' else
('value if true 2' if x['column_name_check_2'] == 'condition_2' else
('value if true 3' if x['column_name_check_3'] == 'condition_3' else 'default_value')),axis=1)
注意:轴 1 的格式值为列/系列
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD