[Python] How can I find the column containing the third NaN value in each row of a DataFrame...

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

  1. Stack

    Stack Membro Participativo

    I have been given a problem to solve for my assignment. Here's the description for my problem:

    In the cell below, you have a DataFrame df that consists of 10 columns of floating-point numbers. Exactly 5 entries in each row are NaN values. For each row of the DataFrame, find the column which contains the third NaN value.

    You should return a Series of column labels: e, c, d, h, d

    nan = np.nan

    data = [[0.04, nan, nan, 0.25, nan, 0.43, 0.71, 0.51, nan, nan],
    [ nan, nan, nan, 0.04, 0.76, nan, nan, 0.67, 0.76, 0.16],
    [ nan, nan, 0.5 , nan, 0.31, 0.4 , nan, nan, 0.24, 0.01],
    [0.49, nan, nan, 0.62, 0.73, 0.26, 0.85, nan, nan, nan],
    [ nan, nan, 0.41, nan, 0.05, nan, 0.61, nan, 0.48, 0.68]]

    columns = list('abcdefghij')

    df = pd.DataFrame(data, columns=columns)

    # write a solution to the question here


    This is my solution:

    result = df.apply(lambda row: row.isna().idxmax(), axis=1)
    print(result)


    My code returns b, a, a, a, b, a, whereas the desired output is e, c, d, h, d. My solution returns the index of the first NaN but according to the question I want the third NaN in each row. How can i do that? Or is there an alternate solution that gives the desired output.

    Continue reading...

Compartilhe esta Página