2878 Get the Size of a DataFrame
Problem Statement
DataFrame players
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.
For the whole problem statement, please refer here.
Plans
Import necessary libraries.
Define the function
getDataframeSize
that accepts a DataFrame as input.Use the DataFrame's methods to extract the number of rows and columns.
Return the results as a list formatted as
[number of rows, number of columns]
.
Solution
Explanation
Importing Libraries
We import the
pandas
library for DataFrame manipulation and List from thetyping
module for type hinting.
Function Definition
A function named
getDataframeSize
is defined, which accepts a single parameter players of typepd.DataFrame
. This function's purpose is to retrieve the dimensions of the provided DataFrame.
Retrieving Rows and Columns
Inside the function, the line
rows
,cols
=players.shape
efficiently uses tuple unpacking. Theshape
attribute of a DataFrame returns a tuple where the first element is the number of rows and the second element is the number of columns. By unpacking it into rows and cols, we can quickly access both values in one statement.
Returning Results
The function concludes with a return statement that outputs a list containing the row and column counts in the specified format:
[rows, cols]
.
Last updated