在 for 循环中引用两个序列,然后根据它们的条件更新第一个序列 - python

Reference two sequences in for loop, then update first sequence based on their conditions - python

尝试在 python for 循环中引用两个序列,例如:

for (col1_row, col2_row) in (df.col1, df.col2)

然后检查两个条件是否成立:

if col1_row = 'nan' and col2_row = '1000 Main Street'

然后用设置值更新df.col1中对应的单元格:

df.col1 == 'Chucky Cheeze Restaurant'

不一定是 for 循环,但我想我会这样解释。寻找最快、最有效的方法。谢谢

我建议不要使用循环,因为速度慢,最好使用 numpy.where 和布尔掩码:

mask = (df.col1 == 'nan') & (df.col2 == '1000 Main Street')
#for oldier pandas versions
#mask = df.col1.isnull() & (df.col2 == '1000 Main Street')
df.col1 = np.where(mask, 'Chucky Cheeze Restaurant', df.col1)

或者:

mask = df.col2 == '1000 Main Street'
df.loc[mask, 'col1'] = df.loc[mask, 'col1'].fillna('Chucky Cheeze Restaurant')