Skip to content
Advertisement

Alternatives to eval() of a string

I have a have dict of dataframes named tr. Each dataframe is named like train_fold_1. To call a dataframe looks like this: tr['train_fold_1'].

I would like to select a section of each of these dataframes and rename them.

This works:

i = 2
X_ = {}
X_[i] = eval("tr['df_train_fold_" + str(i) + "']").iloc[:,1]

But how can I do this process without using eval()?

Advertisement

Answer

You don’t need eval() here at all, as the names for the dataframes are not variable names but just strings used as keys in a dictionary.

i = 2
X_ = {}
X_[i] = tr['df_train_fold_' + str(i)].iloc[:,1]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement