Difficulty: Easy | Acceptance: 84.80% | Paid: No Topics: N/A
Write a solution to get the size of the DataFrame. The size is the number of elements in the DataFrame.
Example 1: Input:
+------------+--------+---------+
| student_id | name | age |
+------------+--------+---------+
| 1 | Alice | 20 |
| 2 | Bob | 22 |
| 3 | Charlie| 19 |
+------------+--------+---------+
Output:
9
Example 2: Input:
+------------+
| student_id |
+------------+
| 1 |
| 2 |
+------------+
Output:
2
Examples
Example 1
Input:
+-----------+----------+-----+-------------+--------------------+
| player_id | name | age | position | team |
+-----------+----------+-----+-------------+--------------------+
| 846 | Mason | 21 | Forward | RealMadrid |
| 749 | Riley | 30 | Winger | Barcelona |
| 155 | Bob | 28 | Striker | ManchesterUnited |
| 583 | Isabella | 32 | Goalkeeper | Liverpool |
| 388 | Zachary | 24 | Midfielder | BayernMunich |
| 883 | Ava | 23 | Defender | Chelsea |
| 355 | Violet | 18 | Striker | Juventus |
| 247 | Thomas | 27 | Striker | ParisSaint-Germain |
| 761 | Jack | 33 | Midfielder | ManchesterCity |
| 642 | Charlie | 36 | Center-back | Arsenal |
+-----------+----------+-----+-------------+--------------------+
Output:
[10, 5]
Explanation: This DataFrame contains 10 rows and 5 columns.
Constraints
0 <= students.length <= 1000
0 <= students.columns <= 1000
Approach 1: Using Built-in Dimensions
Intuition The size of a DataFrame is simply the product of the number of rows and the number of columns. Most data structure libraries provide direct access to these dimensions.
Steps
- Retrieve the number of rows.
- Retrieve the number of columns.
- Return the product of rows and columns.
python
import pandas as pd
def getDataFrameSize(students: pd.DataFrame) -> int:
return students.shape[0] * students.shape[1]Complexity
- Time: O(1)
- Space: O(1)
- Notes: Accessing dimensions is a constant time operation.
Approach 2: Iterative Counting
Intuition If direct dimension properties are not available, we can iterate through every cell in the DataFrame and count them manually.
Steps
- Initialize a counter to 0.
- Iterate through each row.
- For each row, iterate through each column.
- Increment the counter for each cell.
- Return the counter.
python
import pandas as pd
def getDataFrameSize(students: pd.DataFrame) -> int:
count = 0
for i in range(len(students)):
for col in students.columns:
count += 1
return countComplexity
- Time: O(n * m) where n is rows and m is columns.
- Space: O(1)
- Notes: This is inefficient compared to direct property access but demonstrates the underlying logic.