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

Python shift data on every second row from one column to a new column

Newbie to python here…I have a dataframe like this

John
30
Mike
0.0786268
Tyson
0.114889
Gabriel
0.176072
Fiona
0.101895

I need to shift every second row to a new column so it should look like this

John   30
Mike   0.0786268
Tyson  0.114889
Gabriel 0.176072
Fiona   0.101895

Thanks in advanced!

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

>Solution :

This one works for me and the code is easy to understand:

names = []
numbers = []
for i in range(len(df['Names'])):
    if (i % 2) == 0:
        names.append(df['Names'][i])
    else:
        numbers.append(df['Names'][i])

Now the construction of the dataframe:

new_df = pd.DataFrame([names, numbers]).T
new_df.columns = ['Names', 'Numbers']
new_df

The Output:

    Names   Numbers
0   John    30
1   Mike    0.0786268
2   Tyson   0.114889
3   Gabriel 0.176072
4   Fiona   0.101895
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