Python Forum
How to include input as part of variable name
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to include input as part of variable name
#1
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.
Reply
#2
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
Reply
#3
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')
Reply
#4
(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
Mark17 likes this post
Reply
#5

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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to include one script into another? MorningWave 8 427 Mar-21-2024, 10:34 PM
Last Post: MorningWave
  Calling functions by making part of their name with variable crouzilles 4 808 Nov-02-2023, 12:25 PM
Last Post: noisefloor
  how include a python code in notpad++ plugin akbarza 2 620 Sep-25-2023, 08:25 PM
Last Post: deanhystad
  Regex Include and Exclude patterns in Same Expression starzar 2 783 May-23-2023, 09:12 AM
Last Post: Gribouillis
  input variable choice MCL169 7 1,157 Feb-19-2023, 09:00 PM
Last Post: MCL169
  Need help on how to include single quotes on data of variable string hani_hms 5 2,011 Jan-10-2023, 11:26 AM
Last Post: codinglearner
  How to write a part of powershell command as a variable? ilknurg 2 1,115 Jul-26-2022, 11:31 AM
Last Post: ilknurg
  How to use a variable in Python (2.x) to define decimal part? MDRI 4 2,325 May-07-2021, 12:39 AM
Last Post: MDRI
  Can I include text using artist? tetrisbot 0 1,430 Aug-13-2020, 08:13 PM
Last Post: tetrisbot
  trying to input a variable using random.choice python63 9 3,598 Aug-13-2020, 05:37 PM
Last Post: python63

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020