Mark
Mark

Reputation: 25

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()?

Upvotes: 0

Views: 145

Answers (2)

Apo
Apo

Reputation: 338

If you want to get your keys as integer instead of strings (can be useful in some cases) you can replace "eval" with "int".

Upvotes: 0

mkrieger1
mkrieger1

Reputation: 23152

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]

Upvotes: 2

Related Questions