I'm curious to see how do we calculate a new column from a dataframe based on other existing columns and subset of rows.
Example: I have a dataframe with different rooms 111, 222, 333, 444 and each room might have beds AAA, BBB. And I also have bed status per room as occupied or Free. I wanted to calculate a new column - "Active" with following criteria:
- Only one bed per room is active.
- Occupied bed takes first preference to be active in a room.
- If room has only one bed it must be active irrespective of bed status
Sample DataFrame:
Room Bed Status
0 111 AAA Occupied
1 111 BBB Free
2 222 AAA Free
3 333 AAA Free
4 333 BBB Occupied
5 444 BBB Occupied
Expected Output:
Room Bed Status Active
0 111 AAA Occupied True
1 111 BBB Free False
2 222 AAA Free True
3 333 AAA Free False
4 333 BBB Occupied True
5 444 BBB Occupied True
I wanted to convert this to a dictionary and loop through it but have a strong feeling that this could be implemented through pandas in-built functions.
TIA