Mark K
Mark K

Reputation: 9348

Rearrange dataframe, every n rows to columns, left to right, top down

A list of strings.

enter image description here

I want to arrange them into below format. Every 3 rows a group, from left to right, top to down:

enter image description here

By reshaping, I can only achieve below:

import pandas as pd
import numpy as np

data = [

"by Emily Dickinson",
"There is another sky,",
"Ever serene and fair,",
"And there is another sunshine,",
"Though it be darkness there;",
"Never mind faded forests, Austin,",
"Never mind silent fields -",
"Here is a little forest,",
"Whose leaf is ever green;",
"Here is a brighter garden,",
"Where not a frost has been;",
"In its unfading flowers",
"I hear the bright bee hum:",
"Prithee, my brother,",
"Into my garden come!"] 

df = pd.DataFrame(data)

df_1 = pd.DataFrame(np.reshape(df.values,(5,3)))

enter image description here

What's the way to work it out? Thank you.

P.s. the "Row#" and "String" are provided only for clear reading. I want to achieve the rearrangement of content only.

Upvotes: 0

Views: 186

Answers (1)

Md Ziaul Haque
Md Ziaul Haque

Reputation: 144

Just change the reshape parameter and pass order parameter

df_1 = pd.DataFrame(np.reshape(df.values,(3,5),order='F'))

Upvotes: 2

Related Questions