1

I have a dataframe with 2 columns: 'VENDOR_ID' and 'GL_Transaction_Description'. I want to print every row of the 'GL_Transaction_Description' column that has any value from the 'VENDOR_ID' column.

VENDOR_ID GL_Transaction_Description
123 HELLO 345
456 BYE 456
987 THANKS 456

The desired output here would be 'BYE 456' AND 'THANKS 456. My code is as such:

for k in range(len(df)):
    for j in range(len(df)):
        if df['VENDOR_ID'][k] in df['GL_Transaction_Description'][j] and df['VENDOR_ID'][k] != 'nan':
            print(df['GL_Transaction_Description'][j])

But this particular dataframe counts more than 100k rows and it takes forever to run with a nested for loop. Any ideas on how to make this execute faster? I have read that using numpy usually makes things go blazingly faster but I haven't been able to implement it.

John Mantios
  • 67
  • 1
  • 5

3 Answers3

1

Use Boolean Mask

v_list = df['VENDOR_ID'].to_list()
mask = list(map((lambda x: any([(y in x) for y in v_list])), df['GL_Transaction_Description']))

print(df['GL_Transaction_Description'][mask])

Assumed 'VENDOR_ID' is already in dtype of str. If not, then change the line mask = .... to:

mask = list(map((lambda x: any([(str(y) in x) for y in v_list])), df['GL_Transaction_Description']))

We can do it with df.apply() with axis=1. However, list(map()) has better system performance (execution time) than df.apply() on axis=1.

Output:

1       BYE 456
2    THANKS 456
Name: GL_Transaction_Description, dtype: object
SeaBean
  • 22,547
  • 3
  • 13
  • 25
0

You can use boolean Indexing

df.loc[df['GL_Transaction_Description'].isin(df['VENDOR_ID']), 'GL_Transaction_Description']
ashkangh
  • 1,594
  • 1
  • 6
  • 9
0

You can use boolean indexing with the isin function

import pandas as pd
df = pd.DataFrame({'VENDOR_ID': list('abcde') + ['matching_item'],
                  'GL_Transaction_Description': ['trx_descr_' + c for c in list('abcde')] + ['matching_item']})
df

    VENDOR_ID       GL_Transaction_Description
0   a               trx_descr_a
1   b               trx_descr_b
2   c               trx_descr_c
3   d               trx_descr_d
4   e               trx_descr_e
5   matching_item   matching_item

df[df.GL_Transaction_Description.isin(df.VENDOR_ID)].GL_Transaction_Description

5    matching_item
Name: GL_Transaction_Description, dtype: object