Get the Size of a DataFrame - Problem
You're given a pandas DataFrame called players that contains information about sports players. Your task is to determine the dimensions of this DataFrame - specifically, how many rows and columns it contains.
DataFrame Schema:
| Column Name | Type |
|---|---|
| player_id | int |
| name | object |
| age | int |
| position | object |
| ... | ... |
Goal: Write a function that returns the DataFrame's dimensions as a list: [number_of_rows, number_of_columns]
This is a fundamental pandas operation that you'll use frequently in data analysis to understand the size and structure of your datasets.
Input & Output
example_1.py โ Small DataFrame
$
Input:
players = pd.DataFrame({
'player_id': [1, 2, 3],
'name': ['Alice', 'Bob', 'Carol'],
'age': [25, 27, 23],
'position': ['Forward', 'Midfielder', 'Defender']
})
โบ
Output:
[3, 4]
๐ก Note:
The DataFrame has 3 rows (players) and 4 columns (player_id, name, age, position)
example_2.py โ Single Row DataFrame
$
Input:
players = pd.DataFrame({
'player_id': [1],
'name': ['Alice'],
'age': [25]
})
โบ
Output:
[1, 3]
๐ก Note:
The DataFrame has 1 row and 3 columns
example_3.py โ Empty DataFrame
$
Input:
players = pd.DataFrame(columns=['player_id', 'name', 'age', 'position'])
โบ
Output:
[0, 4]
๐ก Note:
The DataFrame has 0 rows but still has 4 defined columns
Visualization
Tap to expand
Understanding the Visualization
1
Identify DataFrame Structure
DataFrame is like a table with rows representing records and columns representing attributes
2
Access Shape Metadata
Pandas stores dimension information as metadata, accessible via .shape property
3
Return Dimensions
Convert the (rows, cols) tuple to [rows, cols] list format
Key Takeaway
๐ฏ Key Insight: The .shape property provides instant access to DataFrame dimensions without any computation, making it the optimal O(1) solution for this problem.
Time & Space Complexity
Time Complexity
O(1)
Shape is stored as metadata, accessed in constant time
โ Linear Growth
Space Complexity
O(1)
Only creating a small list to return the result
โ Linear Space
Constraints
- The DataFrame will be a valid pandas DataFrame object
- Number of rows: 0 โค rows โค 106
- Number of columns: 1 โค columns โค 103
- The DataFrame structure is guaranteed to be consistent
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code