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
  Setting the x-axis to a specific column in a dataframe devansing 0 182 May-23-2021, 12:11 AM
Last Post: devansing
  Add column based on others timste 8 696 Apr-03-2021, 07:39 AM
Last Post: devesh_sahu
Question Pandas - Creating additional column in dataframe from another column Azureaus 2 553 Jan-11-2021, 09:53 PM
Last Post: Azureaus
  Comparing results within a list and appending to pandas dataframe Aryagm 1 454 Dec-17-2020, 01:08 PM
Last Post: palladium
  Extracting rows based on condition on one column Robotguy 2 495 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 1,750 Jul-15-2020, 06:20 PM
Last Post: pawanmtm
  Pandas DataFrame and unmatched column sritsv19 0 970 Jul-07-2020, 12:52 PM
Last Post: sritsv19
  Assigning Column nunique values to another DataFrame column Pythonito 0 557 Jun-25-2020, 05:04 PM
Last Post: Pythonito
  Issue with dataframe column nsadams87xx 0 687 May-29-2020, 02:00 AM
Last Post: nsadams87xx
  Pandas - Dynamic column aggregation based on another column theroadbacktonature 0 779 Apr-17-2020, 04:54 PM
Last Post: theroadbacktonature

Forum Jump:

User Panel Messages

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