Home > Software engineering >  Splitting one record as multiple records in Python
Splitting one record as multiple records in Python

Time:03-11

In python, how can I convert this data like this :

1

into this data like this:

2

CodePudding user response:

You could use np.split(..., 2, axis=1) to split the dataframe vertically into 2 parts:

new_df = pd.concat([x.T.reset_index(drop=True).T for x in np.split(df.set_index('ID'), 2, axis=1)]).sort_index()

Output:

>>> new_df
    0  1  2
ID         
1   0  1  0
1   1  1  1
2   1  1  0
2   0  0  1
3   1  1  1
3   1  0  1
4   1  0  1
4   0  1  0

CodePudding user response:

Try:

pd.concat([df.iloc[:, i:i 3].set_axis([*'XYZ'], axis=1) 
           for i in range(0,6,3)]).sort_index()

Output:

   X  Y  Z
1  0  1  0
1  1  1  1
2  1  1  0
2  0  0  1
3  1  1  1
3  1  0  1
4  1  0  1
4  0  1  0
  • Related