2878 Get the Size of a DataFrame

Problem Statement

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.

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

import pandas as pd
from typing import List

def getDataframeSize(players: pd.DataFrame) -> List[int]:
    # Get the number of rows and columns in the dataframe
    rows, cols = players.shape

    # Return the number of rows and columns as a list
    return [rows, cols]

Explanation

  1. Importing Libraries

    • We import the pandas library for DataFrame manipulation and List from the typing module for type hinting.

  2. Function Definition

    • A function named getDataframeSize is defined, which accepts a single parameter players of type pd.DataFrame. This function's purpose is to retrieve the dimensions of the provided DataFrame.

  3. Retrieving Rows and Columns

    • Inside the function, the line rows, cols = players.shape efficiently uses tuple unpacking. The shape 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.

  4. 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