0

I am trying to lookup string values in two dataframes and I am using Pandas library.

The first dataframe - df_transactions has a list of error codes in the column 'ErrList'

The second dataframe - df_action has a list of errors in one column 'CODE' and the corresponding error in the column 'ACTION'.

I am trying to compare the two strings from these dataframes as below:

ActionLookup_COL = []
ActionLookup = []
for index, transactions in df_transactions.iterrows():
        errorList = transactions['ErrList']
        for index, errorCode in df_action.iterrows():
            eCode = errorCode['Code']
            eAction = errorCode['Action']
            if eCode ==errorList:
                ActionLookup.append(eAction)

        ActionLookup_COL.append(ActionLookup)

df_results['ActionLookup'] = pd.Series(shipmentActionLookup_COL, index=df_results.index)

When I print the dataframe df_results['ActionLookup'], I do not get the action code corresponding to the error code. Please let me know how can I compare the strings in these dataframes

Thanks for your time!

1 Answer 1

1

IIUC you need merge:

pd.merge(df_transactions, df_action, left_on='ErrList', right_on='Code')

Sample:

df_transactions = pd.DataFrame({'ErrList':['a','af','e','d'],
                                'col':[4,5,6,8]})

print (df_transactions)
  ErrList  col
0       a    4
1      af    5
2       e    6
3       d    8

df_action = pd.DataFrame({'Code':['a','af','u','m'],
                          'Action':[1,2,3,4]})

print (df_action)
   Action Code
0       1    a
1       2   af
2       3    u
3       4    m

df_results = pd.merge(df_transactions, df_action, left_on='ErrList', right_on='Code')
print (df_results)
  ErrList  col  Action Code
0       a    4       1    a
1      af    5       2   af

print (df_results['Action'])
  ErrList  col  Action Code
0       a    4       1    a
1      af    5       2   af
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.