0

Here is my dataset:

  •  COL_1 COL_2 COL_3 COL_4 COL_5 COL_8 COL_9
     A col2 col3 col4 col5
     B col2 col3 col4 col5
     C col2 col3 col4 col5
    

I need to move pairs of columns (COL_2 , COL_3 and then COL_4, COL_5) to COL_8 and COL_9 and copy the content of the 1st column (COL_1):

  •  COL_1 COL_8 COL_9
     A col2 col3
     B col2 col3
     C col2 col3
     A col4 col5
     B col4 col5
     C col4 col5
    

How can I do it using Python? Do I need to use loop or are there easier ways to do so?

asked Jan 28, 2022 at 16:09

1 Answer 1

1

Here's a solution:

cols = df.drop('COL_1', axis=1).columns
new_df = pd.concat([pd.concat([df[c] for c in cols[i::2]]) for i in [0,1]], axis=1).assign(A=df['COL_1'])[['A', 0, 1]].set_axis(['COL_1','COL_8','COL_9'], axis=1).reset_index(drop=True)

Output:

>>> new_df
 COL_1 COL_8 COL_9
0 A col2 col3
1 B col2 col3
2 C col2 col3
3 A col4 col5
4 B col4 col5
5 C col4 col5
answered Jan 28, 2022 at 16:16
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.