Skip to main content
Back to problems
#618
Hard Database

Students report by geography

Database
63.5% acceptance
Mar 31, 2026
192
170

No description available.

Solution

Pandas
Time O(1)
Space O(1)
LeetCode
solution.pandas
# Table: Student
# 
# +-------------+---------+
# | Column Name | Type    |
# +-------------+---------+
# | name        | varchar |
# | continent   | varchar |
# +-------------+---------+
# This table may contain duplicate rows.
# Each row of this table indicates the name of a student and the continent they came from.
# 
#  
# 
# A school has students from Asia, Europe, and America.
# 
# Write a solution to pivot the continent column in the Student table so that each name is sorted alphabetically and displayed underneath its corresponding continent. The output headers should be America, Asia, and Europe, respectively.
# 
# The test cases are generated so that the student number from America is not less than either Asia or Europe.
# 
# The result format is in the following example.
#
# Example 1:
# Input:
# Student table:
# +--------+-----------+
# | name   | continent |
# +--------+-----------+
# | Jane   | America   |
# | Pascal | Europe    |
# | Xi     | Asia      |
# | Jack   | America   |
# +--------+-----------+
# Output:
# +---------+------+--------+
# | America | Asia | Europe |
# +---------+------+--------+
# | Jack    | Xi   | Pascal |
# | Jane    | null | null   |
# +---------+------+--------+

import pandas as pd

def geography_report(student: pd.DataFrame) -> pd.DataFrame:
  student = student.sort_values('name')
  student['row_num'] = student.groupby('continent').cumcount()
  result = student.pivot(index='row_num', columns='continent', values='name')
  for col in ['America', 'Asia', 'Europe']:
    if col not in result.columns:
      result[col] = None
  return result[['America', 'Asia', 'Europe']].reset_index(drop=True)