How to divide a Dataframe with another of different size

I got this dataframe

print(tablaFrecuencias)
       i=gramos   100   120   150   170   190   200
    0  Manzanas  2000  1450  1000   550     0     0
    1     Mango     0   250   750  2000  1000     0
    2      Pera     0     0     0   350   650  1000

And I have to get the probability of each cell so I got this new one

totalFrutas = pd.DataFrame(totalFrutas)
print(totalFrutas)
     0
0  5000
1  4000
2  2000

Now I want to divide the first one in the second one like this

2000/5000 1450/5000...
0/4000 250/4000...
0/2000 0/2000...

Try to do this but it gave me this

probabilidadCardinalidad = tablaFrecuencias.div(totalFrutas, axis=0)
print(probabilidadCardinalidad)
    0  100  120  150  170  190  200 i=gramos
0 NaN  NaN  NaN  NaN  NaN  NaN  NaN      NaN
1 NaN  NaN  NaN  NaN  NaN  NaN  NaN      NaN
2 NaN  NaN  NaN  NaN  NaN  NaN  NaN      NaN

This is my full code

tablaFrecuencias = pd.read_csv("BY.csv",header = 0)

totalFrutas = tablaFrecuencias.sum(axis=1)
print(totalFrutas)
totalFrutas1 = totalFrutas.sum(axis=0)
print(totalFrutas1)

probabilidadFruta = totalFrutas.div(totalFrutas1)

totalFrutas = pd.DataFrame(totalFrutas)
print(totalFrutas)

x = tablaFrecuencias.select_dtypes('int').columns.tolist()
tablaFrecuencias[x] = 
tablaFrecuencias.select_dtypes('int').div(totalFrutas.values)
print(tablaFrecuencias)

Answer

First select only int columns using df.select_dtypes. Then use df.div to divide by index:

In [96]: x = tablaFrecuencias.select_dtypes('int').columns.tolist()
In [98]: tablaFrecuencias[x] = tablaFrecuencias.select_dtypes('int').div(totalFrutas.values)

In [99]: tablaFrecuencias
Out[99]: 
   i=gramos  100     120     150    170    190  200
0  Manzanas  0.4  0.2900  0.2000  0.110  0.000  0.0
1     Mango  0.0  0.0625  0.1875  0.500  0.250  0.0
2      Pera  0.0  0.0000  0.0000  0.175  0.325  0.5

Leave a Reply

Your email address will not be published. Required fields are marked *