Python Forum

Full Version: [Solved] How to refer to dataframe column name based on a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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]}"]