Turn columns into python pandas rows

Asked

Viewed 4,543 times

0

I need to make some modifications to a dataframe but I’m not getting it. I’m using pandas.

I have the table below: inserir a descrição da imagem aqui

But I want her to stay that way?

inserir a descrição da imagem aqui

Someone can help me?

2 answers

2

Good afternoon, you can do this using the command melt

Below is the test I did:

Import the input data

import pandas
data = pandas.DataFrame({'Local':['são paulo','rio','bahia'], '01/09/2007': [1,2,0], '01/10/2007': [0,1,0], '01/11/2007': [2,1,1], '01/12/2007': [2,0,3], '01/01/2008': [0,1,1], 'contato':['2345-1244','5422-1244','2345-8674']})

Applies the command melt in the indices, setting Local and contato as ids and adding the variable mes with the value quantidade within the new dataframe, in addition to this I already do the ordering by Local and quantity in descending mode

data = pandas.melt(data.reset_index(), id_vars=['Local', 'contato'], 
var_name='mes', value_name='quantidade').sort(['Local','quantidade'], ascending=False)

The new dataframe was created, but we still have some undesirable lines that contains index value, then simply do the removal of these lines

data = data[data.mes.str.contains("index") == False]

Follow the result

I hope I’ve helped Hug

-1

Hello, all right, I found a really cool solution, which solved the problem I will post the image here! , df.stack()

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.