How to change one column of data to multiple column based on row using Python Pandas?

Viewed 40

I dont know if I put the question correctly.. For example, I want

1
0
1
0
1
0
1
0

change into

1  0  1  
0  1  0
1  0  x

The first list should not be changed.. and change the type to DataFrame..

I try use numpy.array, flatten the array. and reshape to columns using reshape(-1,3).T .. but since there are some missing value to it.. I cannot reshape the array properly..

1 Answers

A possible solution would be to add the missing values to the array before resizing.

Starting point:

import numpy as np
import pandas as pd

# I assume you flattened the array.
data = np.array([1, 0, 1, 0, 1, 0, 1, 0, ])

Adding the new data based on the required shape and fill value:

new_shape = (3, 3)
fill_value = np.NaN

missing_length = np.product(new_shape) - data.size
missing_array = np.full(missing_length, fill_value)

data = np.hstack([data, missing_array])

Then apply the reshape and convert it to a dataframe:

data = data.reshape(new_shape)

df = pd.DataFrame(data)
print(df)

output:

     0    1    2
0  1.0  0.0  1.0
1  0.0  1.0  0.0
2  1.0  0.0  NaN
Related