Python Forum
[Solved] How to refer to dataframe column name based on a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Solved] How to refer to dataframe column name based on a list
I am new to python, so my question may not have the correct terminology. I hope my intent is clear enough.

ma_list = [5,10]


A. Based on ma_list, I created two new columns (MA_5 & MA_10) in the df:

for ma in ma_list:
    df_ma[f'MA_{ma}'] = df_ma.mid_c.rolling(window = ma).mean()


B. I then create a new column DIFF based on the difference of the 2 moving averages above:

df_ma['DIFF'] = df_ma.MA_5 - df_ma.MA_10

How do I accomplish step B without manually entering the column name?

I tried the following, I knew it was wrong before I ran the code. How would I accomplish this.

df_ma['DIFF'] = df_ma.[f"MA_{ma_list[0]}"] - df_ma.[f"MA_{ma_list[1]}"]
Thank you.
Solved it. Should be like so:

df_ma['DIFF'] = df_ma[f"MA_{ma_list[0]}"] - df_ma[f"MA_{ma_list[1]}"]

Possibly Related Threads…
Thread Author Replies Views Last Post
  New Dataframe Column Based on Several Conditions nb1214 1 362 Nov-16-2021, 10:52 PM
Last Post: jefsummers
  Putting column name to dataframe, can't work. jonah88888 1 560 Sep-28-2021, 07:45 PM
Last Post: deanhystad
  update values in one dataframe based on another dataframe - Pandas iliasb 2 2,120 Aug-14-2021, 12:38 PM
Last Post: jefsummers
  Pandas Data frame column condition check based on length of the value aditi06 1 842 Jul-28-2021, 11:08 AM
Last Post: jefsummers
  Setting the x-axis to a specific column in a dataframe devansing 0 859 May-23-2021, 12:11 AM
Last Post: devansing
  Add column based on others timste 8 1,659 Apr-03-2021, 07:39 AM
Last Post: devesh_sahu
Question Pandas - Creating additional column in dataframe from another column Azureaus 2 1,240 Jan-11-2021, 09:53 PM
Last Post: Azureaus
  Comparing results within a list and appending to pandas dataframe Aryagm 1 1,017 Dec-17-2020, 01:08 PM
Last Post: palladium
  Extracting rows based on condition on one column Robotguy 2 1,008 Aug-07-2020, 02:27 AM
Last Post: Robotguy
  Filter data based on a value from another dataframe column and create a file using lo pawanmtm 1 2,735 Jul-15-2020, 06:20 PM
Last Post: pawanmtm

Forum Jump:

User Panel Messages

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