0

In a loop, I have built a string to be used as a column restriction in a panda dataframe :

conditions = pd.DataFrame()

for index, fold in df.iterrows():
    first_row = True
    for elem in fold['include_months']:
        if first_row: 
            condition = f"""('MonthNumber_"""+str(elem)+"' == 1)" 
            first_row = False
        else:
            condition += f""" | ('MonthNumber_"""+str(elem)+"' == 1)" 
        

But I get an error with condition applied to panda column:

X_train = X_train[condition]

KeyError: "(X_train['MonthNumber_1'] == 1)| (X_train['MonthNumber_2'] == 1)"

How to fix it please?

1 Answer 1

1

Make condition not a string

condition = (X_train['MonthNumber_1'] == 1) | (X_train['MonthNumber_2'] == 1)

# since you're override your variable, it's best to make a copy
X_train = X_train[condition].copy()

You can also use query if you want to use a string form:

condition = 'MonthNumber_1 == 1 | MonthNumber_2 == 1'
X_train = X_train.query(condition).copy()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but how to make condition not a string with :this code: train_months = f"""(X_train['MonthNumber_"""+str(elem)+"'] == 1)" ?
X_train.filter(like='MonthNumber').eq(1).any(axis=1).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.