bigboat
bigboat

Reputation: 299

How to run a number of functions by parsing a list in python?

I have a class that returns a pandas.DataFrame with a number of columns. I'd like to plot these columns individually. One way to do it is by

lst=[result.df.open, result.df.close] 
for i in lst: i.plot()

however I'd like to do something like

lst=['open', 'close']
for i in lst: result.df.i.plot()

but this doesn't work because I'm parsing strings. I'm wondering if there's a way to do this? maybe through the use of {} curly brackets but I'm not sure?

Upvotes: 0

Views: 45

Answers (2)

Lior Cohen
Lior Cohen

Reputation: 5745

In addition to the other answers. If you want to dynamically perform “df.i” when i is a string, you should use getattr(df, i)

foo.bar is equivalent to getattr(foo, ‘bar’)

Upvotes: 1

Snedecor
Snedecor

Reputation: 739

Supposing df is the pandas dataframe and lst is the list of string corresponding to the columns you would like to plot:

lst=['open', 'close']
for i in lst: 
    df[i].plot()

Upvotes: 0

Related Questions