DataFrame players:
+-------------+--------+
| Column Name | Type |
+-------------+--------+
| player_id | int |
| name | object |
| age | int |
| position | object |
| ... | ... |
+-------------+--------+
Write a solution to calculate and display the number of rows and columns of players.
Return the result as an array:
[number of rows, number of columns]
The result format is in the following example.
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.
This approach utilizes the built-in attributes of a DataFrame in Python to extract the number of rows and columns. Specifically, DataFrame.shape is used to get a tuple containing the dimensions of the DataFrame.
The function get_dataframe_size utilizes the shape attribute of a pandas DataFrame, which returns a tuple with the number of rows and columns.
Time Complexity: O(1) because accessing the shape attribute is a constant-time operation.
Space Complexity: O(1), as we only return a fixed-size list.
Another simple way to determine the number of rows and columns is by using DataFrame properties len() and DataFrame.columns to count each explicitly.
This approach calculates the number of rows by using the len() function on the DataFrame and the number of columns by counting the length of the columns property of the DataFrame.
Time Complexity: O(1) for both row and column size retrieval since the operations are constant time.
Space Complexity: O(1), as we only store and return a fixed-size list.
| Approach | Complexity |
|---|---|
| Using Built-in DataFrame Attributes | Time Complexity: O(1) because accessing the shape attribute is a constant-time operation. |
| Using DataFrame Properties | Time Complexity: O(1) for both row and column size retrieval since the operations are constant time. |
Minimum Size Subarray Sum - Leetcode 209 - Python • NeetCode • 110,629 views views
Watch 9 more video solutions →Practice Get the Size of a DataFrame with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor