Skip to content
Advertisement

Python Pandas – Lookup a variable column depending on another column’s value

I’m trying to use the value of one cell to find the value of a cell in another column. The first cell value (‘source’) dictates which column to lookup.

JavaScript

My required output value in the ‘output’ column is a lookup of the ‘source’:

JavaScript

Failed attempts

JavaScript

This results in a ValueError: Wrong number of items passed 4, placement implies 1 because the df['source'] passes in a Series, not a string. I tried converting to a string using:

JavaScript

which gave error AttributeError: ‘Series’ object has no attribute ‘convertDTypes’.

Working solution

I found a solution might by iterating through the rows using:

JavaScript

However, this post suggests iterating is a bad idea. The code doesn’t seem very elegant, either.

I feel I’ve missed something basic here; this really should not be that hard.

Advertisement

Answer

Let us do numpy way since lookup will not longer work in the future version

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement