yuonger741
yuonger741

Reputation: 137

How to transpose a certain rows of a column using pandas

How do I transpose a column with every certain number of rows?

Say that I have a column with 1000 rows and I'd like to transpose this column every 100 rows. Then I shall have ten rows afterwards.

It should be transposing something like this:

  column
1 data1
2 data2
3 data3
4 data4
...
1000 data1000

to

1 data1 data2 ... data100
2 data11 data12 ... data200
...
10 data901 data902 ... data1000

Upvotes: 1

Views: 624

Answers (2)

BENY
BENY

Reputation: 323356

Use:

df.reset_index(drop=True,inplace=True)
df['New']=df.index//2# change here to 100 in your data
df['col']=df.New.groupby(df.New).cumcount()
df.pivot('New','col','column')
Out[205]: 
col      0      1
New              
0    data1  data2
1    data3  data4
2    data5  data6

Upvotes: 1

rafaelc
rafaelc

Reputation: 59274

You can slice it using iloc and then use the default constructor

Suppose you have

df = pd.DataFrame(index=range(1,1001), data={"col": ["data{}".format(i) for i in range(1,1001)]})

     col
1    data1
2    data2
3    data3
4    data4
5    data5
.
.
.
995  data995
996  data996
997  data997
998  data998
999  data999
1000 data1000

Then

>>> vals = [df.iloc[x:x+100].col.tolist() for x in range(0, 1000, 100)]
>>> pd.DataFrame(vals)

    0       1       2       3       4       ... 94      95      96      97      98      99 
0   data1   data2   data3   data4   data5   ... data95  data96  data97  data98  data99  data100
.
.
.
9   data901 data902 data903 data904 data905 ... data995 data996 data997 data998 data999 data1000

Upvotes: 1

Related Questions