'Splitting one record as multiple records in Python

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

1

into this data like this:

2



Solution 1:[1]

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 richardec
Solution 2 Scott Boston