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?
1 Answer 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
user17242583
Sign up to request clarification or add additional context in comments.
Comments
lang-py