【发布时间】:2020-03-01 03:54:52
【问题描述】:
问题:我正在尝试使用 for 循环逐行遍历数据框。但它没有按预期工作。我知道有 iterrows() 和 itertuple() 我想试验 for 循环。
你能告诉我这是哪里出错了吗?
样本数据
data3 = {"one":['101', '102', '103' , '104'],
"two":['101', '105', '106', '104'],
"three": ['102', '5', '107', '108'],
"other": ['101', '102', '103' , '104']
}
df3 = pd.DataFrame(data3)
目标:逐行检查“二”列,以及“一”列中是否存在“二”列的值 然后创建一个值为“del”的新列“new_col”。如果“一”列中不存在该值,则 将“new_col”创建为“keep”。例如,如果“二”列有 101,我想将它与“一”列的所有值进行比较
我的代码:
dfToList1 = df3['two'].tolist()
for x in dfToList1:
if x in df3['one'].values:
df3['new_col'] = 'del'
else:
df3['new_col'] = 'keep'
然后我可以用类似'none'的字符串替换'two'中与'one'匹配的值
df3.loc[df3['new_col'] == 'del', 'two'] = 'none'
我的输出:
理想情况下,在第 2 行和第 3 行,“two”中的 5 和 107 不包含在“one”中,因此第 2 行和第 3 行中的 new_col 应该具有值“keep”,但我没有得到它。
one other three two new_col
0 101 101 102 101 del
1 102 102 5 105 del
2 103 103 107 106 del
3 104 104 108 104 del
预期输出
one other three two new_col
0 101 101 102 101 del
1 102 102 5 105 keep
2 103 103 107 106 keep
3 104 104 108 104 del
【问题讨论】:
-
您的目标与您的预期输出不符。您说您希望
new_col成为del或keep但您的预期输出还有其他内容。你能澄清一下吗? -
你是对的。按要求更新。