When we deal with a Pandas DataFrame
, it is often we need to convert values of cells according specific conditions.
Suppose that we have a DataFrame that contains city info, and we need may specific cities into different tiers. One of my former colleagues provided such a solution:
In this case, np.where
is used to map items. Nice try, but if we have much more tiers, this way will be redundant. Yes, we can use a recursion, but we have a much simpler solution to solve this problem.
In a previous post, I mentioned using a dictionary to replace the if...else
logic, and here we go, we will use dict
here as well.
First, we can create a mapping dict.
The we can use a simple dict.get()
to replace the items in a DataFrame. Here is the magic:
Yes, just one dict
and one line of code, and the problem has been easily solved. Super easy, right?