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.
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.
1import pandas as pd
2
3def get_dataframe_size(df):
4 return list(df.shape)
5
6# Example usage
7players = pd.DataFrame({
8 "player_id": [846, 749, 155, 583, 388, 883, 355, 247, 761, 642],
9 "name": ["Mason", "Riley", "Bob", "Isabella", "Zachary", "Ava", "Violet", "Thomas", "Jack", "Charlie"],
10 "age": [21, 30, 28, 32, 24, 23, 18, 27, 33, 36],
11 "position": ["Forward", "Winger", "Striker", "Goalkeeper", "Midfielder", "Defender", "Striker", "Striker", "Midfielder", "Center-back"],
12 "team": ["RealMadrid", "Barcelona", "ManchesterUnited", "Liverpool", "BayernMunich", "Chelsea", "Juventus", "ParisSaint-Germain", "ManchesterCity", "Arsenal"]
13})
14
15print(get_dataframe_size(players)) # Output: [10, 5]
The function get_dataframe_size
utilizes the shape
attribute of a pandas DataFrame, which returns a tuple with the number of rows and columns.
Another simple way to determine the number of rows and columns is by using DataFrame properties len()
and DataFrame.columns
to count each explicitly.
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.
1import pandas as pd
2
3def get_dataframe_size(df):
4 num_rows = len(df)
5 num_columns = len(df.columns)
6 return [num_rows, num_columns]
7
8# Example usage
9players = pd.DataFrame({
10 "player_id": [846, 749, 155, 583, 388, 883, 355, 247, 761, 642],
11 "name": ["Mason", "Riley", "Bob", "Isabella", "Zachary", "Ava", "Violet", "Thomas", "Jack", "Charlie"],
12 "age": [21, 30, 28, 32, 24, 23, 18, 27, 33, 36],
13 "position": ["Forward", "Winger", "Striker", "Goalkeeper", "Midfielder", "Defender", "Striker", "Striker", "Midfielder", "Center-back"],
14 "team": ["RealMadrid", "Barcelona", "ManchesterUnited", "Liverpool", "BayernMunich", "Chelsea", "Juventus", "ParisSaint-Germain", "ManchesterCity", "Arsenal"]
15})
16
17print(get_dataframe_size(players)) # Output: [10, 5]
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.