gpt4 book ai didi

python - 在 Pandas 中使用 ELIF 创建列

转载 作者:太空狗 更新时间:2023-10-29 16:58:42 24 4
gpt4 key购买 nike

问题

我无法弄清楚如何根据其他两列中的值创建新的 DataFrame 列。我需要使用 if/elif/else 逻辑。但是我找到的所有文档和示例都只显示 if/else 逻辑。这是我正在尝试做的示例:

代码

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

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

最佳答案

如果您有多个分支语句,最好创建一个接受一行的函数,然后沿 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)

关于python - 在 Pandas 中使用 ELIF 创建列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18194404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com