Python 使用for循环遍历数据帧以替换现有值

Python 使用for循环遍历数据帧以替换现有值,python,pandas,for-loop,Python,Pandas,For Loop,问题:我试图通过使用for循环逐行循环数据帧。但它并没有按预期工作。我知道有ItErrors()和itertuple(),我想用for循环进行实验 你能告诉我哪里出了问题吗 样本数据 data3 = {"one":['101', '102', '103' , '104'], "two":['101', '105', '106', '104'], "three": ['102', '5', '107', '108'], "other": ['101', '102',

问题:我试图通过使用for循环逐行循环数据帧。但它并没有按预期工作。我知道有ItErrors()和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)
目标:检查每行的“2”列,以及“1”列中是否存在“2”列的值 然后创建一个值为“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'
然后我可以将“two”中与“one”匹配的值替换为类似“none”的字符串

df3.loc[df3['new_col'] == 'del', 'two'] = 'none'
我的输出:

dfToList1 = df3['two'].tolist()
for x in dfToList1:
   if x in df3['one'].values:
       df3['new_col'] = 'del'
   else:
       df3['new_col'] = 'keep'
理想情况下,在第2行和第3行,“2”中的5和107不包含在“1”中,因此第2行和第3行中的新列应具有“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

使用
np.where

df3['new_col'] = np.where(df3['two'].isin(df3['one']), 'del', 'keep')
结果:

   one  two three new_col
0  101  101   102     del
1  102  105     5    keep
2  103  106   107    keep
3  104  104   108     del
与和一起使用以检查

df3['newcol']=np.where(~df3.two.isin(df3.one),'keep','del')

或通过列“一”和列“二”中的任何公共值进行选择:

df3['newcol']=np.where(~df3.one.isin(df3.loc[df3.two.eq(df3.one),'two']),'keep','del')
print(df3)

   one  two three other newcol
0  101  101   102   101    del
1  102  105     5   102   keep
2  103  106   107   103   keep
3  104  104   108   104    del
详细信息

two_coincident_one=df3.loc[df3.two.eq(df3.one),'two']
print(two_coincident_one)
0    101
3    104
Name: two, dtype: object


~df3.one.isin(two_coincident_one)

0    False
1     True
2     True
3    False
Name: one, dtype: bool

您的目标与预期输出不匹配。你说你想把新的颜色变成del或者keep,但是你的预期输出有别的东西。你能澄清一下吗?你是对的。按要求更新。我的错。它起作用了。我尝试了NP.No..但不使用.In():如果这对你有用,请考虑将其标记为“回答”,这很好。你能给我一点提示吗?这个比df3['newcol']=np.where(~df3.two.isin(df4.one),'keep','del')之前建议的更好。只需使用
Series.eq
,即可在两列之间选择匹配的行。使用
DataFrame.loc
,选择与第1列一致的第2列行。然后使用Series.isin,值​​在前面的列中选择的列1的行被选中(请参见详细信息),而使用上述方法,您只提到了列2的行,其值​​选择列1中存在的