首页 > 解决方案 > 我可以使用布尔循环找到两个 df cols 相等的值然后设置 df1['col1'] = df2['col2']

问题描述

我必须找到df2 col1等于的值df1 col1,然后从同一行df1 col2替换为。df2 col2

我已经尝试过.isin()(可能不正确)和多个条件,即if (df1['col1'] == df2['col1']) & (df1['col3'] == 'x index')

i=0
for i in df1:
     if df1['col1'].isin(df2['col1']):
          df1['col2'] = df2['col2']
     else df1['col1'].isin(df3):
          df1['col2'] = df['col3']
 i+=1

标签: pythonpandasloopsiterator

解决方案


请,如果您找到不使用循环的解决方案,它总是更好。在您的情况下,查找另一列中的行可以通过内部连接来解决。我希望这是一个可以解决您的问题的代码。

In [1]:
## Set the exemple with replicable code
import pandas as pd

cols = ['col1', 'col2'] 
data = [[100, 150],
        [220, 240],
        [80, 60]
       ]

df1 = pd.DataFrame(data=data, columns=cols).set_index('col1')


cols = ['col1', 'col2'] 
data = [[111, 0],
        [220, 0],
        [80, 0]
       ]

df2 = pd.DataFrame(data=data, columns=cols).set_index('col1')

## Get all the rows from df1 col1 that are in df2 col1
df_merge = df1.merge(df2, left_index=True, right_index=True, how='inner', suffixes=('_df1', '_df2'))
df_merge

Out [1]:
        col2_df1    col2_df2
col1        
220     240         0
80      60          0

然后做一个左连接将值添加col2 df2col2 df1

In [2]:
df1 = df1.merge(df_merge, how='left', left_index=True, right_index=True)
df1.drop(axis=1, columns=['col2', 'col2_df1'], inplace=True)
df1.rename(columns={'col2_df2': 'df2'}, inplace=True)
df1

Out [2]:
    df2
col1    
100 NaN
220 0.0
80  0.0

推荐阅读