Skip to content Skip to sidebar Skip to footer

Python Pandas Match Two Indexes And Value Of Column

I want to match between indexes of rows in two different dfs, and if the indexes are the same, I want to go to the second df, iterate through it's columns, and if the value of a co

Solution 1:

You can first create index from names column by set_index, replace values by dict and add_prefix.

Then join it to original:

cols = ['col1','col2','col3']
DF2 = DF2.set_index('names')[cols].replace({'V':'DF2', 'X':np.nan}).add_prefix('total_')
print (DF2) 
      total_col1 total_col2 total_col3
names                                 
bbb          DF2        DF2        NaN
zzz          NaN        NaN        DF2

df = df.join(DF2, on='names')
print (df)
  names col1 col2 col3  total total_col1 total_col2 total_col3
0   bbb    V    V    X      2        DF2        DF2        NaN
1   ccc    V    X    X      1        NaN        NaN        NaN

Post a Comment for "Python Pandas Match Two Indexes And Value Of Column"