问题描述
限时送ChatGPT账号..我正在尝试在数据框中创建一个新列,用 1 标记驯养的动物.我正在使用 for 循环,但出于某种原因,该循环仅选取 宠物
列表.dog
、cat
和 gerbil
都应在 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代码>.这包括
dog
或 cat
条目.您应该一次检查 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:关键词]
发布评论