Washington Muniz
Washington Muniz

Reputation: 100

How to change columns to rows with pandas?

This is my df:

import pandas as pd

categoria = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
dados1 = [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
dados2 = [144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4, 129.2]

df = pd.DataFrame([dados1, dados2], columns = categoria)
print(df)
     Jan    Feb    Mar    Apr    May  ...    Aug    Sep    Oct    Nov    Dec
0   29.9   71.5  106.4  129.2  144.0  ...  148.5  216.4  194.1   95.6   54.4
1  144.0  176.0  135.6  148.5  216.4  ...   54.4   29.9   71.5  106.4  129.2

But I'd like something like this:

     dados1   dados2
Jan    29.9    144.0
Feb    71.5    176.0
Mar   106.4    135.6

What I tried so far:

df1 = pd.pivot_table(df, index = categoria, columns = [dados1, dados2])

But I've got an error:

ValueError: Grouper and axis must be same length

What should I do?

Upvotes: 1

Views: 51

Answers (2)

BENY
BENY

Reputation: 323226

IIUC

df = pd.DataFrame(zip(dados1, dados2), index = categoria)
df
         0      1
Jan   29.9  144.0
Feb   71.5  176.0
Mar  106.4  135.6
Apr  129.2  148.5
May  144.0  216.4
Jun  176.0  194.1
Jul  135.6   95.6
Aug  148.5   54.4
Sep  216.4   29.9
Oct  194.1   71.5
Nov   95.6  106.4
Dec   54.4  129.2

Upvotes: 3

Krishna
Krishna

Reputation: 481

I think you can use transpose() function and rename the columns as you need.

df=df.transpose()
df.columns=['dados1','dados2']

enter image description here

Upvotes: 2

Related Questions