FunkyMore
FunkyMore

Reputation: 243

How to iterate 2 DataFrames and fill a column in Python

I have 2 data frames for example:

df1:

index  A    C
   3   a  NaN
   4   b  NaN
   6   c  NaN
   7   d  NaN
   9   e  NaN
  10   f  NaN
  12   g  NaN
  13   h  NaN
  15   i  NaN
  16   j  NaN

df2(N as index):

N    Name
2     Tom
5    Jack
8    Rose
11  Marrie
14    Lucy

I would like to compare the index values of these two dfs and fill column 'C' in df1 for Name as below:

   A  B   C
   3  a  Tom
   4  b  Tom
   6  c  Jack
   7  d  Jack
   9  e  Rose
  10  f  Rose
  12  g  Marrie
  13  h  Marrie
  15  i  Lucy
  16  j  Lucy

Upvotes: 1

Views: 41

Answers (1)

BENY
BENY

Reputation: 323366

Seems like you need merge_asof

#df1=df1.reset_index()
#df2=df2.reset_index()
pd.merge_asof(df1,df2,left_on='index',right_on='N').drop(['C','N'],1)
Out[143]: 
   index  A    Name
0      3  a     Tom
1      4  b     Tom
2      6  c    Jack
3      7  d    Jack
4      9  e    Rose
5     10  f    Rose
6     12  g  Marrie
7     13  h  Marrie
8     15  i    Lucy
9     16  j    Lucy

Upvotes: 3

Related Questions