Python Forum
Interate for loop over certain columns in dataframe
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Interate for loop over certain columns in dataframe
I am working on my bachelor thesis where i want to run a loop over certain columns in my dataframe and create future and lagged returns of a portfolio.
I works fine for the first loop(future) but in the second loop(lagged) it creates a tickers_future_lagged

Keep in mind i load the data from a CSV-file and want to do this for whole index of stocks and several periods of lagged returns.

import pandas as pd
df_1 = pd.read_csv("data.csv")
df_1 = df_1.set_index('Date')
tickers = (['DANSKE.CO', 'NOVO.CO', 'ORSTED.CO'])

for tickers in df.columns:
    if df[tickers].dtype == 'float':
        df[tickers+'_future'] = df[tickers].shift(-1)/df[tickers]-1
for tickers in df.columns:
    if df[tickers].dtype == 'float':
        df[tickers+'_lagged'] = df[tickers].shift(1)/df[tickers]-1
for the first loop it creates 3 new colums with tickers_future that is correct
the the second loop it creates 6 new colums, both a tickers_lagged and a tickers_future_lagged and i only want the tickers_lagged and not the tickers_future_lagged

How do i run the loop so i only create the right column?

Hope you understand my question.

Best regards, Finpyth from Denmark.
First loop changes the dataframe and you have another set of columns when calling df.columns in line #11.

To fix this, just store column names in a variable, before changing the df, e.g.
col_to_process = df.columns

for tickers in col_to_process:
    ... your code (_future)

for tickers in col_to_process:
    ... your code (_lagged)
Thank you very much!

Possibly Related Threads…
Thread Author Replies Views Last Post
  Convert several columns to int in dataframe Krayna 2 498 May-21-2021, 08:55 AM
Last Post: Krayna
  Outputs "NaN" after "DataFrame columns" function? epsilon 7 1,069 Jan-27-2021, 10:59 AM
Last Post: epsilon
  Adapting a dataframe to the some of columns flyway 2 872 Aug-12-2020, 07:21 AM
Last Post: flyway
  Difference of two columns in Pandas dataframe zinho 2 1,491 Jun-17-2020, 03:36 PM
Last Post: zinho
  DataFrame: To print a column value which is not null out of 5 columns mani 2 971 Mar-18-2020, 06:07 AM
Last Post: mani
Question Dividing a single column of dataframe into multiple columns based on char length darpInd 2 976 Mar-14-2020, 09:19 AM
Last Post: scidam
  newbie: loop, modify dataframe cells expat_th 5 1,458 Mar-03-2020, 09:05 PM
Last Post: jefsummers
  How to highlight dataframe columns SriRajesh 1 980 Feb-28-2020, 11:02 PM
Last Post: Marbelous
  Does the order of columns in the DataFrame matter? new_to_python 11 2,342 Feb-17-2020, 12:32 AM
Last Post: scidam
  Pandas dataframe columns collapsed in Spyder when printing UniKlixX 2 2,484 Nov-04-2019, 07:00 AM
Last Post: UniKlixX

Forum Jump:

User Panel Messages

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