[Python] Count number of characters in each row and drop if all are below a certain number

Discussão em 'Python' iniciado por Stack, Dezembro 21, 2024.

  1. Stack

    Stack Membro Participativo

    I have a dataframe with many columns, all of which contain text data mixed with NaNs.

    I want to count the number of characters in each cell in each column and then drop any rows where all the columns have less than 5 characters (if any cells have more than 5 characters, then the row is not dropped).

    I was considering making a new column with str.len for each column and then filter out rows using that, but it seems very cumbersome.

    Example:

    >>> df
    column_1 column_2 column_3
    0 werhi dsfhjk dh ---> not filtered because some columns have more than 5 characters
    1 sgds fuo g ---> filtered
    2 wqyuio dsklh fhkjfj
    3 fhi d fgho ---> filtered
    4 sadfhkj sdjfkhs yyisdk

    >>> df_filtered
    column_1 column_2 column_3
    0 werhio dsfhjk dh
    2 wqyuio dsfjklh fhkjfj
    4 sadfhkj sdjfkhs yyisdk

    Continue reading...

Compartilhe esta Página