Use pandas to aggregate, pivot, and label
Problem Description
You are provided with two Pandas DataFrames: users and orders. Your task is to perform a series of data manipulation operations including merging, aggregation, pivoting, and conditional labeling, reusing the intermediate merged DataFrame across steps.
Input DataFrames
users DataFrame
This DataFrame contains user demographic information.
| Column | Description |
|---|---|
user_id | Unique identifier for each user. |
is_member | Binary flag (1 for member, 0 for non-member). |
state | User's geographical state. |
age | User's age. |
Example users data:
user_id | is_member | state | age
--------|-----------|-------|----
101 | 1 | CA | 29
102 | 0 | NY | 41
103 | 1 | CA | 35
104 | 0 | TX | 50
orders DataFrame
This DataFrame contains order details.
| Column | Description |
|---|---|
order_id | Unique identifier for each order. |
user_id | Foreign key linking to the users DataFrame. |
channel | The marketing channel through which the order was placed (e.g., 'SMS', 'Email', 'Organic'). |
amount | The monetary value of the order. |
status | The delivery status of the order (e.g., 'delivered', 'undelivered'). |
Example orders data:
order_id | user_id | channel | amount | status
---------|---------|---------|--------|-----------
7001 | 101 | SMS | 12.00 | delivered
7002 | 102 | Email | 5.00 | delivered
7003 | 103 | SMS | 7.00 | delivered
7004 | 103 | Email | 4.00 | delivered
7005 | 101 | Organic | 3.50 | delivered
7006 | 104 | SMS | 6.00 | undelivered
Tasks
You must complete the following steps sequentially, using the merged DataFrame as the base for subsequent operations where applicable.
Step 1: Merge and Aggregate Revenue
- Perform a
left joinof theordersDataFrame with theusersDataFrame onuser_id. - From this merged DataFrame, compute two separate outputs:
- (a) Total Delivered Revenue by Channel: Calculate the sum of
amountfor all orders withstatus == 'delivered', grouped bychannel. - (b) Delivered Revenue by Channel for Members Only: Calculate the sum of
amountfor orders withstatus == 'delivered'placed by users whereis_member == 1, grouped bychannel.
- (a) Total Delivered Revenue by Channel: Calculate the sum of
- Both results should be presented as Pandas DataFrames.
Step 2: Create a 2x2 Pivot Table
- Using the merged DataFrame (from Step 1), create a pivot table focusing on delivered revenue.
- The pivot table should have
is_member(0 or 1) as its index andchannelas its columns, specifically restricted to['SMS', 'Email']. - The values in the pivot table should be the sum of
amountfor delivered orders. - Missing cells in the pivot table should be filled with
0. - Utilize the
pivot_tablefunction withaggfunc='sum'.
Step 3: Compute Per-State Counts
- From the merged DataFrame, calculate the following metrics for each
state:- Total number of orders (
size). - Number of unique purchasers (
nuniqueofuser_id).
- Total number of orders (
- Return the top 2 states based on their total number of orders, sorted in descending order.
Step 4: Add a Binary High-Value Flag
- Add a new column named
high_value_flagto the merged DataFrame. - Set
high_value_flag = 1if a user meets either of the following conditions, otherwise set it to0:- The user's total lifetime delivered
amountis greater than or equal to15. - The user has placed two or more delivered orders via the 'SMS' channel.
- The user's total lifetime delivered
- Ensure you use
np.whereand leverage priorgroupbyaggregations to efficiently compute these conditions and avoidSettingWithCopyWarningissues. - Display the
headof the final DataFrame, including the newly addedhigh_value_flagcolumn and other relevant user/order details.
AI interview prep
Core dilemma
Ensuring efficient, correct, and idiomatic Pandas data manipulation, especially when handling intermediate aggregations and avoiding common pitfalls like `SettingWithCopyWarning`, to derive accurate insights from complex data relationships.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Use pandas to aggregate, pivot, and label
Problem Description
You are provided with two Pandas DataFrames: users and orders. Your task is to perform a series of data manipulation operations including merging, aggregation, pivoting, and conditional labeling, reusing the intermediate merged DataFrame across steps.
Input DataFrames
users DataFrame
This DataFrame contains user demographic information.
| Column | Description |
|---|---|
user_id | Unique identifier for each user. |
is_member | Binary flag (1 for member, 0 for non-member). |
state | User's geographical state. |
age | User's age. |
Example users data:
user_id | is_member | state | age
--------|-----------|-------|----
101 | 1 | CA | 29
102 | 0 | NY | 41
103 | 1 | CA | 35
104 | 0 | TX | 50
orders DataFrame
This DataFrame contains order details.
| Column | Description |
|---|---|
order_id | Unique identifier for each order. |
user_id | Foreign key linking to the users DataFrame. |
channel | The marketing channel through which the order was placed (e.g., 'SMS', 'Email', 'Organic'). |
amount | The monetary value of the order. |
status | The delivery status of the order (e.g., 'delivered', 'undelivered'). |
Example orders data:
order_id | user_id | channel | amount | status
---------|---------|---------|--------|-----------
7001 | 101 | SMS | 12.00 | delivered
7002 | 102 | Email | 5.00 | delivered
7003 | 103 | SMS | 7.00 | delivered
7004 | 103 | Email | 4.00 | delivered
7005 | 101 | Organic | 3.50 | delivered
7006 | 104 | SMS | 6.00 | undelivered
Tasks
You must complete the following steps sequentially, using the merged DataFrame as the base for subsequent operations where applicable.
Step 1: Merge and Aggregate Revenue
- Perform a
left joinof theordersDataFrame with theusersDataFrame onuser_id. - From this merged DataFrame, compute two separate outputs:
- (a) Total Delivered Revenue by Channel: Calculate the sum of
amountfor all orders withstatus == 'delivered', grouped bychannel. - (b) Delivered Revenue by Channel for Members Only: Calculate the sum of
amountfor orders withstatus == 'delivered'placed by users whereis_member == 1, grouped bychannel.
- (a) Total Delivered Revenue by Channel: Calculate the sum of
- Both results should be presented as Pandas DataFrames.
Step 2: Create a 2x2 Pivot Table
- Using the merged DataFrame (from Step 1), create a pivot table focusing on delivered revenue.
- The pivot table should have
is_member(0 or 1) as its index andchannelas its columns, specifically restricted to['SMS', 'Email']. - The values in the pivot table should be the sum of
amountfor delivered orders. - Missing cells in the pivot table should be filled with
0. - Utilize the
pivot_tablefunction withaggfunc='sum'.
Step 3: Compute Per-State Counts
- From the merged DataFrame, calculate the following metrics for each
state:- Total number of orders (
size). - Number of unique purchasers (
nuniqueofuser_id).
- Total number of orders (
- Return the top 2 states based on their total number of orders, sorted in descending order.
Step 4: Add a Binary High-Value Flag
- Add a new column named
high_value_flagto the merged DataFrame. - Set
high_value_flag = 1if a user meets either of the following conditions, otherwise set it to0:- The user's total lifetime delivered
amountis greater than or equal to15. - The user has placed two or more delivered orders via the 'SMS' channel.
- The user's total lifetime delivered
- Ensure you use
np.whereand leverage priorgroupbyaggregations to efficiently compute these conditions and avoidSettingWithCopyWarningissues. - Display the
headof the final DataFrame, including the newly addedhigh_value_flagcolumn and other relevant user/order details.