Separate Dataframe Column in List

Asked

Viewed 33 times

-3

I have a Dataframe with three columns:

 Categoria Label   Porcentagem
 Cat1      Label1  40
 Cat1      Label2  10
 Cat1      Label3  25
 Cat1      Label4  25
 Cat2      Label1  50
 Cat2      Label2  50
 Cat3      Label3  100

I need to turn the Percentage column into a list, preserving the 4 Label entries, by Category, of type:

 lista_porcent = [[40, 10, 25, 25],
                [50,50,0,0],
                [0,0,100,0]]

How to do?

Thanks!!!

  • please show which output you want

  • Output is list_percent = [[40, 10, 25, 25], [50,50,0,0], [0,0,100,0]]

  • then you want a list as output and not a new dataframe with a new column, right?

  • that’s right! I need to separate the percentage column according to my 3 categories, keep the 4 label entries (filling with zero if you don’t have the 4 Labels for the category), and turn it into a list

1 answer

0


What you need is a pivot_table:

table=pd.pivot_table(data=df,index='Label',values='Porcentagem', columns='Categoria').fillna(0)

print([table[k].to_list() for k in table.columns])

Output:

[[40.0, 10.0, 25.0, 25.0], [50.0, 50.0, 0.0, 0.0], [0.0, 0.0, 100.0, 0.0]]

Browser other questions tagged

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