how to match two dataFrame in python
<p>I have two dataFrame in Python.
The first one is df1:</p>

<pre><code>'ID'    'B' 
   AA    10
   BB    20
   CC    30
   DD    40
</code></pre>

<p>The second one is df2:</p>

<pre><code> 'ID'  'C'  'D'
    BB   30   0
    DD   35   0
</code></pre>

<p>What I want to get finally is like df3:</p>

<pre><code>'ID'  'C'  'D'
   BB   30   20
   DD   35   40
</code></pre>

<p>how to reach this goal?
my code is:</p>

<pre><code>for i in df.ID
  if len(df2.ID[df2.ID==i]):
    df2.D[df2.ID==i]=df1.B[df2.ID==i]
</code></pre>

<p>but it doesn't work.</p>

<p>So first of all, I've interpreted the question differently, since your description is rather ambiguous. Mine boils down to this:</p>

<p>df1 is this data structure:</p>

<pre><code>ID   B            &lt;- column names
AA  10
BB  20
CC  30
DD  40
</code></pre>

<p>df2 is this data structure:</p>

<pre><code>ID   C  D        &lt;- column names
BB  30  0
DD  35  0
</code></pre>

<p>Dataframes have a merge option, if you wanted to merge based on index the following code would work:</p>

<pre><code>import pandas as pd

df1 = pd.DataFrame(
    [
        ['AA', 10],
        ['BB', 20],
        ['CC', 30],
        ['DD', 40],
    ],
    columns=['ID','B'],
)
df2 = pd.DataFrame(
    [
        ['BB', 30, 0],
        ['DD', 35, 0],
    ], columns=['ID', 'C', 'D']
)

df3 = pd.merge(df1, df2, on='ID')
</code></pre>

<p>Now df3 only contains rows with ID's in both df1 and df2:</p>

<pre><code>ID   B   C  D    &lt;- column names
BB  20  30  0
DD  40  35  0
</code></pre>

<p>Now you were trying to remove D, and fill it in with column B, a.k.a</p>

<pre><code>ID  C  D
BB 30 20 
DD 35 40
</code></pre>

<p>Something that can be done with these simple steps:</p>

<pre><code>df3 = pd.merge(df1, df2, on='ID') # merge them
df3.D = df3['B']                  # set D to B's values
del df3['B']                      # remove B from df3
</code></pre>

<p>Or to summarize:</p>

<pre><code>def match(df1, df2):
    df3 = pd.merge(df1, df2, on='ID') # merge them
    df3.D = df3['B']                  # set D to B's values
    del df3['B']                      # remove B from df3
    return df3
</code></pre>

python dataframe