mercredi 22 janvier 2020

Python - if str in df.column enter in an if statement

Basically my code import some configuration from a config file, where the user can toggle on/off part of the code. The config file looks something like and it is a json file:

condition1: ['str1', 1] condition2: ['str2', 1]

The string is the name it will be assigned to the df column and the integer can be 1 or 0 to toggle on or off part of the code.

At the beginning of the code, if the integer is set to 1 the string is used to create a column in a dataframe.

for (k, v) in config_file.items():
     if v[1] == 1:
        df[v[0]] = np.nan

So now I will have a column called 'str1' only if the integer for condition1 was 1. At a certain point in the code, I need to first verify that the integer for both conditions is set to 1, and then I need to select all the rows containing a value 1.

if condition1[1] == 1 or condition2[1] == 1:
    if (len(df[df['str1'] == 1]) > 0 or len(df[df['str2'] == 1]) > 0):

The problem now is that if one of the two conditions is set to 0, let's say condition1, then the column df['str2'] will not be created and len(df[df['str2'] == 1]) > 0 will throw an error.

Is there a way to tell python to evaluate part of the condition only if the column/variable exist? Thank you very much for your support.

Aucun commentaire:

Enregistrer un commentaire