Operations between elements of different Python lists

1

I need to perform a division operation between items from two different lists.

import pandas as pd

df = pd.read_csv('este_mes_subastas2.csv', sep=',')

a = list(df['Subastas'])
b = list(df['Impresiones'])
print a

>>> 
[39496098, 82823040, 81547406, 87863582, 84646788, 46192389, 42343494, 84741570, 90058153, 90184289, 87520960]
print b

>>>
[39496098, 456, 81521406, 63125282, 112236788, 678765389, 42343494, 84741570, 90058153, 90184289, 87520960]

I am looking to do this mathematical function for all the elements of the (a[0] / b[0])*100 lists. The following formula would be (a[1] / b[1])*100 , (a[2] / b[2])*100 and so on until element 11 of both lists

    
asked by Martin Bouhier 14.01.2018 в 20:59
source

2 answers

1

As I said it makes no sense to create Python lists and iterate over them, which is tremendously inefficient, when vectorizing the operation in Pandas is trivial:

df["Resultado"] = df.Subastas / df.Impresiones * 100

A reproducible example:

import sys
import pandas as pd

if sys.version_info[0] < 3:
    from StringIO import StringIO # Python 2
else:
    from io import StringIO       # Python 3


csv = StringIO('''\
Subastas,Impresiones
405,52
75,87
0,5
0,45
785,0
454,96
2,5
''')

df = pd.read_csv(csv, sep=',')
df["Resultado"] = df.Subastas / df.Impresiones * 100

Result:

>>> df

   Subastas  Impresiones   Resultado
0       405           52  778.846154
1        75           87   86.206897
2         0            0    0.000000
3         0           45    0.000000
4       785            0         inf
5       454           96  472.916667
6         2            5   40.000000

The division between 0 does not give an error, it is assigned a value of inf (infinite).

    
answered by 15.01.2018 / 19:28
source
0

You can do the following:

for itemA, itemB in zip(a,b):
     print((itemA / itemB) * 100)

What zip() does with the two lists is to return an iterator of tuples that you can see doing this:

>>> list(zip(a,b))
[(39496098, 39496098), (82823040, 456), (81547406, 81521406), (87863582, 63125282), (84646788, 112236788), (46192389, 678765389), (42343494, 42343494), (84741570, 84741570), (90058153, 90058153), (90184289, 90184289), (87520960, 87520960)]
    
answered by 14.01.2018 в 21:08