[Python] Pandas Groupby Show Non-Matching Values

Discussão em 'Python' iniciado por Stack, Junho 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following dataframe:

    data = [['123456ABCD234567', 'A'], ['8502', 'A'],
    ['74523654894WRZI3', 'B'], ['85CGNK6987541236', 'B'],
    ['WF85Z4HJ95R4CF2V', 'C'], ['VB52FG85RT74DF96', 'C'],
    ['WERTZ852146', 'D'], ['APUNGF', 'D']
    ]
    df = pd.DataFrame(data, columns=['CODE', 'STOCK'])
    df

    CODE STOCK
    0 123456ABCD234567 A
    1 8502 A
    2 74523654894WRZI3 B
    3 85CGNK6987541236 B
    4 WF85Z4HJ95R4CF2V C
    5 VB52FG85RT74DF96 C
    6 WERTZ852146 D
    7 APUNGF D


    Each stock is part of various codes. The code should have a length of 16 characters. My objective is to filter out any stocks that have no codes attached which are not composed of 16 characters. In this example, stock A has at least one code with a length of 16 characters, so it should be kept. However, stock D has no codes with a length of 16 characters.

    I believe this can be accomplished using the groupby-function in Pandas.

    Ultimately, I aim at obtaining below output:

    CODE STOCK
    6 WERTZ852146 D
    7 APUNGF D


    Many thanks for any suggestions in advance!

    Continue reading...

Compartilhe esta Página