Gunnar
Gunnar

Reputation: 105

How can I use a string in a loop to be used in a dataframe command? Using Python 3

Say I have dataframe named population that contains the series age and education. I am interested in running the command pd.qcut so for example for age I would write pd.qcut(population.age.values, [0, .25, .5, .75, 1],['a','b','c','d']).

I would like to do this for each column (and replace each column) in a loop form, as:

col_name = ['age', 'education']
for i in col_name:

   population.i=pd.qcut(population.i.values, [0, .25, .5, .75, 1],['a','b','c','d'])

But I cannot find the right function that opens the string for me in population.i.values. I tried Poped(i) but it didn't work.

Thanks in advance.

Upvotes: 1

Views: 41

Answers (1)

mgc
mgc

Reputation: 5443

You have to use population[i] instead of population.i.

The pandas documentation about indexing explain how to access Series corresponding to colname by doing frame[colname].

When you are doing population.i (called Attribute Access in the doc) pandas is looking for a columns who names actually 'i'.

Upvotes: 1

Related Questions