Home > Enterprise >  Columns manipulation - python
Columns manipulation - python

Time:01-29

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?

CodePudding user response:

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
  •  Tags:  
  • Related