问题:我正在尝试使用for循环逐行循环遍历数据帧。但是它没有按要求工作。我知道有iterrows()和itertuple(),我想尝试for循环。
你能告诉我哪里出问题了吗?
样本数据
data3 = {"one":['101','102','103','104'],"two":['101','105','106',"three": ['102','5','107','108'],"other": ['101','104']
}
df3 = pd.DataFrame(data3)
目标:每行检查列“ two”,并且在“ one”列中是否存在“ two”列的值 然后使用值“ del”创建一个新列“ new_col”。如果该值在“一”列中不存在,则 将“ new_col”创建为“ keep”。例如,如果列“ two”具有101,我想将其与列“ one”的所有值进行比较
我的代码:
dfToList1 = df3['two'].tolist()
for x in dfToList1:
if x in df3['one'].values:
df3['new_col'] = 'del'
else:
df3['new_col'] = 'keep'
然后我可以用'none'这样的字符串替换与'one'匹配的'two'中的值
df3.loc[df3['new_col'] == 'del','two'] = 'none'
我的输出:
理想情况下,第二行和第三行中的“ two”中的5和107不包含在“ one”中,因此第二行和第三行中的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