Reputation: 398
I have this line of code that works.
price = df1.loc[:, ['price', 'date']]
I need to emulate this is as a loop with other metrics like sales and revenue. Is this possible? i.e How do I get Python to reference a word in the list both with and without quotation marks?
listx = [price,sales, revenue]
for a in listx:
a = df1.loc[:, ['a', 'date']]
Upvotes: 0
Views: 87
Reputation: 6483
IIUC, you could do something like this, using a list comprehension:
listx = ['price','sales', 'revenue']
price, sales, revenue=[df1.loc[:, [a, 'date']] for a in listx]
For a general way, this could be an approach using globals
:
listx = ['price','sales', 'revenue']
for a in listx:
globals().update({a:df1.loc[:, [a, 'date']]})
As is requested in the comments, please provide a minimal reproducible example in the future.
Upvotes: 2
Reputation: 3929
One way to do it is to save it in a dict:
metrics = {}
listx = ['price', 'sales', 'revenue']
for a in listx:
metrics[a] = df1.loc[:, [a, 'date']]
Now you can access the metrics with metric['sales']
etc.
Maybe I misunderstood your question. Please provide a minimal reproducible example in the future.
Upvotes: 2