lundi 20 mars 2017

Print value if items of different dataframes are equal but respect condition with Pandas

I have 2 dataframes df and table:

import pandas as pd

df = pd.DataFrame({'A':[0,2,6,3,6,8,9,2,1,0],
                   'B':[1,1,1,1,3,3,5,5,5,2]})

table = pd.DataFrame({'A':[[0,4],[5,10],[2,8],[9,10],[0,8],[9,10],[5,10],[0,4],[1,7],[8,10]],
                      'B':[1,1,2,2,3,3,4,4,5,5],
                      'C':[[1,2,3],[4,5,6],[7,8],[9],[10,11,12],[13,14],[15],[16,17],[18,19,20],[21,22,23,24]]})

my goal is to print the content of the generic row of table['C'] whenever the following conditions are met:

  • item of df['B'] is equal to table['B']
  • item of df['A'] is belongs to the range of table['A']

I was able to achieve my goal by using the following lines of code:

for i,row1 in df.iterrows():
    for j, row2 in table.iterrows():
        if row1['B'] == row2['B'] and (row1['A'] in range(row2['A'][0],row2['A'][1])):
                print(row2['C'])

I would like to know if it is possible to get the same result in a more efficient and elegant way since df and table may be very large.

Aucun commentaire:

Enregistrer un commentaire