Obtener la longitud de un DataFrame

Escribe una solución para calcular y mostrar el número de filas y columnas de los jugadores. Retorna el resultado como un arreglo: [número de filas, número de columnas]

#pandas#data-inspection#introduction-to-pandas
DataFrame players:
+-------------+--------+
| Column Name | Type   |
+-------------+--------+
| player_id   | int    |
| name        | object |
| age         | int    |
| position    | object |
| ...         | ...    |
+-------------+--------+

El formato del resultado se muestra en el siguiente ejemplo.

Ejemplo 1:

Entrada:

+-----------+----------+-----+-------------+--------------------+
| 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            |
+-----------+----------+-----+-------------+--------------------+

Salida:

[10, 5]

Explicación:
Este DataFrame contiene 10 filas y 5 columnas.

Solución

import pandas as pd

from typing import List


def getDataframeSize(players: pd.DataFrame) -> List[int]:
    return [len(players), len(players.columns)]


def test_getDataframeSize():
    columns = {
        'player_id': 'Int64',
        'name': 'object',
        'age': 'Int64',
        'position': 'object',
        'team': 'object'
    }
    data = [
        [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'],
    ]
    players = pd.DataFrame(data, columns=columns.keys()).astype(columns)

    expected = [10, 5]
    got = getDataframeSize(players)

    assert got == expected

slackmart blog © 2024