简体   繁体   中英

Python Pandas - check if value exists in 1 dataframe and update value in another dataframe based on results

I have 2 dataframes.

Orders and Receipts .

Both Orders and Receipts have a column named Request Number .

Orders have an additional Column named Received .

I need to compare ['Request Number'] columns and determine whether there's a matching field (eg 123456) inside either dataframes.

If it exists in either dataframes Received value in Orders should change to True else stay False .

I tried the following with no luck - it output False , despite knowing there's matching fields.

orders['Received'] = orders['Request Number'].apply(lambda x: True if x in receipts['Request Number'] else False)

Any suggestions why it's not working?

Thanks in advanced.

Use Series.isin for check membership:

orders['Received'] = orders['Request Number'].isin(receipts['Request Number'])

Any suggestions why it's not working?

You can check using the in operator :

Using the Python in operator on a Series tests for membership in the index, not membership among the values.

So possible solution is convert values to numpy array:

orders['Received'] = (orders['Request Number']
                        .apply(lambda x: x in receipts['Request Number'].to_numpy()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM