How to divide two dataframes with different length and duplicated indexs in Python
<p>Here is my code and I want to get the expected output, but, division of dataframes does not work, what is wrong here?    </p>

<pre><code>import pandas as pd
data1 = {'name':['A', 'C', 'D'], 'cond_a':['B','B','B'], 'value':[10,12,14]}
data2 = {'name':['A', 'C', 'D','D','A'], 'cond_a':['G','G','G','G','G'], 'value':[5,6,7,3,2]}

df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)

df1.set_index('name', inplace=True)
df2.set_index('name', inplace=True)


df2['new_col'] = df2['value'] / df1['value']
</code></pre>

<p>expected output:</p>

<pre><code>     cond_a  value    new_col
name        
   A    G     5        5/10
   C    G     6        6/12
   D    G     7        7/14
   D    G     3        3/14        
   A    G     2        2/10
</code></pre>

<p>What doesn't work in your case is not DataFrame division, which you can easily check:</p>

<pre><code>df2['value'] / df1['value']

Out[]:
name
A    0.500000
A    0.200000
C    0.500000
D    0.500000
D    0.214286
Name: value, dtype: float64
</code></pre>

<p>The problem is that in the process of this division <code>pandas</code> loses track of the order of index <code>name</code>. Then when you are trying to assign the result back to the <code>df2</code>, you have duplicates in your index <code>name</code> and <code>pandas</code> doesn't know how to merge them, because it is an ambiguous situation to have. In general having duplicates in your index is not a good idea. Get rid of the duplicates and your code will work.</p>

python pandas