How can I convert a 1-column dataframe array (in python) to an 8 column dataframe?
I have tried to use Numpy reshape function as follows:
data = []
for x in range(0, 24):
data.append(x)
df = pd.DataFrame(data)
reshaped = pd.DataFrame(np.reshape(df.columns.to_numpy(), (1, 8)), columns=["Heading1", "Heading2", "Heading3", "Heading4", "Heading5", "Heading6", "Heading7", "Heading8"])
but when doing so, I get the following error:
ValueError: cannot reshape array of size 1 into shape (8)
So, I'm expecting an output of 3 rows x 8 columns of numbers between 0 and 24
Do you have any suggestions?
CodePudding user response:
I'm making some assumptions about what you are after, namely a 8 columns with 3 rows where your original range is spread sequentially across the new shorter rows.
reshaped = pd.DataFrame(np.reshape(df.to_numpy(), (3, 8)), columns=["Heading1", "Heading2", "Heading3", "Heading4", "Heading5", "Heading6", "Heading7", "Heading8"])
Heading1 Heading2 Heading3 Heading4 Heading5 Heading6 Heading7 \
0 0 1 2 3 4 5 6
1 8 9 10 11 12 13 14
2 16 17 18 19 20 21 22
Heading8
0 7
1 15
2 23
Two big differences here:
- We don't want a numpy array made up of the dataframe's columns. We want one of the whole 1x24 dataframe. So just
df.to_numpy()
- The shape of the outputted reshaped numpy array has to share the same multiple as the original
1*24 != 1*8
, instead we need a 3 by 8 sized array.
CodePudding user response:
Try this:
data = np.arange(24)
df = pd.DataFrame(data, columns=['value'])
new_data = np.array(df['value']).reshape(-1, 8)
new_df = pd.DataFrame(new_data)
new_df.columns = ["Heading1", "Heading2", "Heading3", "Heading4", "Heading5", "Heading6", "Heading7", "Heading8"]
Output:
Heading1 Heading2 Heading3 Heading4 Heading5 Heading6 Heading7 Heading8
0 0 1 2 3 4 5 6 7
1 8 9 10 11 12 13 14 15
2 16 17 18 19 20 21 22 23