For循环在应该赋值时赋值

2024-05-26 07:47:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用for循环来根据另一列的值为一列指定两个值中的一个。我创建了一个要分配给一个元素的项目列表,使用else来分配其他元素。但是,我的代码只是将else值赋给列。我也试过elif,但没用。这是我的密码:

#create list of aggressive reasons
aggressive = ['AGGRESSIVE - ANIMAL', 'AGGRESSIVE - PEOPLE', 'BITES']

#create new column assigning 'Aggressive' or 'Not Aggressive'
for reason in top_dogs_reason['Reason']:
    if reason in aggressive:
        top_dogs_reason['Aggression'] = 'Aggressive'
    else:
        top_dogs_reason['Aggression'] = 'Not Aggressive'

我的新专栏top\u dogs\u reason['Aggressive']只具有Not Aggressive的值。有人能告诉我为什么吗?你知道吗


Tags: 项目in元素列表fortopcreatenot
1条回答
网友
1楼 · 发布于 2024-05-26 07:47:01

您应该使用loc来分配这样的东西,这些东西隔离了要更新的数据帧的一部分。第一行获取“aggressive”列中的值,其中“Reason”列的值包含在列表“aggressive1”中。第二行在“原因”列中查找其而不是的位置。你知道吗

top_dogs_reason[top_dogs_reason['Reason'].isin(aggressive), 'Aggression'] = 'Aggressive'
top_dogs_reason[~top_dogs_reason['Reason'].isin(aggressive), 'Aggression'] = 'Not Aggressive'

或者在Roganjosh解释的一行中使用np.where,这很像excel if/else语句。所以这里我们说,如果理性是侵略性的,给我们“侵略性的”,否则“不侵略性的”,并将其分配到“侵略性”一栏:

top_dogs_reason['Aggression'] = np.where(top_dogs_reason['Reason'].isin(aggressive), "Aggressive", "Not Aggressive")

或者ankyƏu91的答案,它使用.map映射值。这是一种有效的方法,可以将字典提供给熊猫系列,对于系列中的每个值,它都会查看字典中的键并返回相应的值:

top_dogs_reason['reason'].isin(aggressive).map({True:'Aggressive',False:'Not Aggressive'})

相关问题 更多 >