Skip to main content
Back to problems
#2985
Easy Database

Calculate compressed mean

Database
86.3% acceptance
Mar 31, 2026
14
6

No description available.

Solution

Pandas
Time O(n)
Space O(1)
LeetCode
solution.pandas
# Table: Orders
# 
# +-------------------+------+
# | Column Name       | Type |
# +-------------------+------+
# | order_id          | int  |
# | item_count        | int  |
# | order_occurrences | int  |
# +-------------------+------+
# order_id is column of unique values for this table.
# This table contains order_id, item_count, and order_occurrences.
# 
# Write a solution to calculate the average number of items per order, rounded to 2 decimal places.
# 
# Return the result table in any order.
# 
# The result format is in the following example.
#
# Example 1:
# Input:
# Orders table:
# +----------+------------+-------------------+
# | order_id | item_count | order_occurrences |
# +----------+------------+-------------------+
# | 10       | 1          | 500               |
# | 11       | 2          | 1000              |
# | 12       | 3          | 800               |
# | 13       | 4          | 1000              |
# +----------+------------+-------------------+
# Output
# +-------------------------+
# | average_items_per_order |
# +-------------------------+
# | 2.70                    |
# +-------------------------+
# Explanation
# The calculation is as follows:
# - Total items: (1 * 500) + (2 * 1000) + (3 * 800) + (4 * 1000) = 8900
# - Total orders: 500 + 1000 + 800 + 1000 = 3300
# - Therefore, the average items per order is 8900 / 3300 = 2.70

import pandas as pd

def compressed_mean(orders: pd.DataFrame) -> pd.DataFrame:
  total_items = (orders['item_count'] * orders['order_occurrences']).sum()
  total_orders = orders['order_occurrences'].sum()
  avg = round(total_items / total_orders, 2)
  return pd.DataFrame({'average_items_per_order': [avg]})