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
#1
Question 
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.
Reply
#2
Solved it. Should be like so:

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


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to most effectively unpack list of name-value pair dictionaries in a dataframe? zlim 1 652 Nov-07-2023, 10:56 PM
Last Post: zlim
  [solved] list of list with one or more empty one paul18fr 5 2,386 Oct-04-2023, 09:08 AM
Last Post: jeffreyteague
  concat 3 columns of dataframe to one column flash77 2 841 Oct-03-2023, 09:29 PM
Last Post: flash77
  HTML Decoder pandas dataframe column mbrown009 3 1,027 Sep-29-2023, 05:56 PM
Last Post: deanhystad
  attempt to split values from within a dataframe column mbrown009 8 2,354 Apr-10-2023, 02:06 AM
Last Post: mbrown009
  Make unique id in vectorized way based on text data column with similarity scoring ill8 0 889 Dec-12-2022, 03:22 AM
Last Post: ill8
  Pandas Dataframe Filtering based on rows mvdlm 0 1,430 Apr-02-2022, 06:39 PM
Last Post: mvdlm
  New Dataframe Column Based on Several Conditions nb1214 1 1,800 Nov-16-2021, 10:52 PM
Last Post: jefsummers
  Putting column name to dataframe, can't work. jonah88888 1 1,834 Sep-28-2021, 07:45 PM
Last Post: deanhystad
  update values in one dataframe based on another dataframe - Pandas iliasb 2 9,256 Aug-14-2021, 12:38 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

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