使用 np.where 的 for 循环

编程入门 行业动态 更新时间:2024-10-25 16:21:30
本文介绍了使用 np.where 的 for 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试在数据框中创建一个新列,用 1 标记驯养的动物.我正在使用 for 循环,但出于某种原因,该循环仅选取 宠物列表.dogcatgerbil 都应在 domesticated 列下分配为 1.任何人都有解决此问题的方法或更好的方法?

I'm trying to create a new column in a dataframe that labels animals that are domesticated with a 1. I'm using a for loop, but for some reason, the loop only picks up the last item in the pets list. dog, cat, and gerbil should all be assigned a 1 under the domesticated column. Anyone have a fix for this or a better approach?

df = pd.DataFrame(
    {'creature': ['dog', 'cat', 'gerbil', 'mouse', 'donkey']
    })

pets = ['dog', 'cat', 'gerbil']

for pet in pets:
    df['domesticated'] = np.where(df['creature']==pet, 1, 0)

df

推荐答案

您在上次循环迭代中将所有非沙鼠设置为 0.也就是说,当 pet 在上次迭代中为 gerbil 时,所有不等于 gerbil 的条目将对应于 0.这包括 dogcat 条目.您应该一次检查 pets 中的所有值.试试这个:

You are setting all non gerbil to 0 in your last loop iteration. That is, when pet is gerbil in your last iteration, ALL entries that are not equal to gerbil will correspond to 0. This includes entries that are dog or cat. You should check all values in pets at once. Try this:

df['domesticated'] = df['creature'].apply(lambda x: 1 if x in pets else 0)

如果你想坚持使用 np.where:

df['domesticated'] = np.where(df['creature'].isin(pets), 1, 0)

这篇关于使用 np.where 的 for 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-26 03:45:43,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:np

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!