[Python] how to create a dataframe filter condition dynamically

Discussão em 'Python' iniciado por Stack, Maio 8, 2025.

  1. Stack

    Stack Membro Participativo

    I have a function that returns a data frame and a date string.

    pattern 2025-05-07
    a 104

    b 87

    c 34

    I am applying the function on multiple dates to generate similar data frames as above. The resulting dataframes are concatenated to generate a final dataframe as below.

    pattern 2025-05-07 2025-05-08
    a 104.0 7.0

    b 87.0 0.0

    c 34.0 2.0

    I am trying to generate a filter condition using the date strings received as a output of the functions. Since, I do not have any control on the input dates, I am trying to generate a filter condition dynamically as below -

    for index, date_str in enumerate(date_str_list):
    if index == 0:
    filter_condition = final_df[date_str] > 1
    else:
    filter_condition = filter_condition & final_df[date_str] > 1
    print('filter_condition',filter_condition)
    final_filtered_df = final_df[filter_condition]
    print('final_filtered_df\n',final_filtered_df)


    When I apply the above filter I get an empty dataframe.

    But when I run the hardcoded filter I get proper data.

    final_filtered_df = final_df[(final_df['2025-05-07'] > 1) & (final_df['2025-05-08'] > 1)]


    Can anyone let me know where I am going wrong. Would appreciate help on this.

    Continue reading...

Compartilhe esta Página