如何迭代2个DataFrame并填充Python

时间:2018-04-11 20:34:56

标签: python pandas dataframe

我有2个数据框,例如:

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为索引):

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

我想比较这两个dfs和填充列的索引值' C'在df1中的姓名如下:

   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

1 个答案:

答案 0 :(得分:3)

好像你需要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