Python Forum
[Solved] How to refer to dataframe column name based on a list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: [Solved] How to refer to dataframe column name based on a list (/thread-33689.html)



[Solved] How to refer to dataframe column name based on a list - lorensa74 - May-17-2021

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.


RE: How to refer to dataframe column name based on a list - lorensa74 - May-17-2021

Solved it. Should be like so:

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