pythonpandasdataframelist

Python recognise with and without quotation marks


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']]

Solution

  • 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']]})