Python Forum
How to include input as part of variable name - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to include input as part of variable name (/thread-34909.html)



How to include input as part of variable name - Mark17 - Sep-14-2021

Hi all,

Here's a code snippet:

MA_list = [10,50,100]

for per in MA_list:
    df_per = df.copy()
    df_per[per_MA] = df_per['Adj Close'].rolling(window=per).mean() 
What I'm trying to do is create new dataframes named df_10, df_50, and df_100. I want them to be df with an additional column named 10_MA, 50_MA, or 100_MA, respectively. The last line defines the additional column as a moving average.

This doesn't work. I get an error saying per_MA is not recognized. I want it to be the name of the new column with list element (a number) substituted for per. What's the best way to do this?

Thanks!

Mark

P.S. I haven't worked out the rest, which is why I just included this portion.


RE: How to include input as part of variable name - Mark17 - Sep-14-2021

This works:

    MA_list = [10,50,100]

    col_names = []
    
    for i in range(len(MA_list)):
        col_names.append(str(MA_list[i])+'_MA')  #this converts integer period to string and concatenates with '_MA'
    
    df_dict = {}
    
    for j in range(len(col_names)):
        df_dict['df'+str(j)] = df.copy()
        df_dict['df'+str(j)][col_names[j]] = df_name['Adj Close'].rolling(window=per).mean() 
        print('First five lines of df'+str(j)+' are:')
        print(df_dict['df'+str(j)].head())
        print()
Any suggestions of how to make this more efficient? One thing I'd like is to not repeat 'df'+str(j) three times but maybe it's no big deal.

Mark


RE: How to include input as part of variable name - deanhystad - Sep-14-2021

periods = {10:None, 50:None, 100:None}

for period in periods:
    new_df = df.copy()
    new_df[f'{period}_MA'] = df_name['Adj Close'].rolling(window=period).mean() 
    periods[period] = new_df
    print(f'First five lines of period {period} are:')
    print(new_df.head(), '\n')



RE: How to include input as part of variable name - snippsat - Sep-14-2021

(Sep-14-2021, 02:26 PM)Mark17 Wrote: Any suggestions of how to make this more efficient?
A general advice so is loop this in Pandas often unnecessary and also slow.
Can sometime be necessary to loop,but often can this be unnecessary as may thinking of doing it same way as standard Python.
So in Pandas work in different way than standard Python.
A Beginner’s Guide to Optimizing Pandas Code for Speed in Pandas
Quote:This brings us to a few basic conclusions on optimizing Pandas code:
  1. Avoid loops; they’re slow and, in most common use cases, unnecessary.
  2. If you must loop, use apply(), not iteration functions.
  3. Vectorization is usually better than scalar operations. Most common operations in Pandas can be vectorized.
  4. Vector operations on NumPy arrays are more efficient than on native Pandas series.
Se that no loop is used in this this intro.
10 minutes to pandas


RE: How to include input as part of variable name - Mark17 - Oct-01-2021


I don't believe I saw this before. Thanks for posting it, snippsat. This is exactly what I need to get into my blood. I've been trying to understand it better but not there yet.