Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create columns from single column pandas

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..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

You are looking for shift:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading