Home > Software engineering >  Create columns from single column pandas
Create columns from single column pandas

Time:03-20

I have a dataframe with multiple columns but I want to focus on a specific one. From this column called "Value" I would like to create N columns where N is a window of the column "Value". I'll try to explain it better in the following image

screenshot of Excel showing the windowing

In this particular case, my parameter N is equal to 5, but of course it can change dynamically. Starting from the first row, I want to take the next 5 values and transpose them to columns, the same for the second row, and so on so forth..

Can anyone help me to solve this problem?

My idea was to try to iterate over rows and assign values to subset of columns like this

df[['D1','D2','D3','D4','D5']].loc[1] = ['1','2','3','4','5']

but it seems that it's not possible.

CodePudding user response:

You are looking for shift:

for i in range(1, 6):
    df[f"D{i}"] = df["VALUE"].shift(-i)
  • Related