遍历熊猫数据框以使用for循环替换现有值

问题:我正在尝试使用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
lixiangzyz 回答:遍历熊猫数据框以使用for循环替换现有值

使用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
,

使用np.whereSeries.eqSeries.isin进行检查。

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']),'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
本文链接:https://www.f2er.com/3164120.html

大家都在问