How to group a column containing a list in pandas? - Python3

Asked

Viewed 464 times

1

Talk to the guys! I have a problem with pandas who can’t find a solution. I have the following dataset:

inserir a descrição da imagem aqui

I wanted to make a group where, for each year, and in each category present that year, it would add up the votes of each of these categories.

In this example output would be something like:

inserir a descrição da imagem aqui

The problem that always when I call . groupby trying to pass the genres it gives me the error Typeerror: unhashable type: 'list'

One thing I have is a list of all the generos in the dataframe, I don’t know if it will help

Here Cód q I am using. The mentioned dataset is obtained from qtdgeneroyearv2

qtdgeneroyearv2 = pd.DataFrame(dataframefilmes) 
qtdgeneroyearv2[['genres', 'year', 'votes']].groupby(['year', 'genres']).sum()

Someone to give me a light? Thank you!

  • Hello hello hello, you need to share more data, the code you are using...only two tables is not enough...however, take a look at this topic that can help you.... https://stackoverflow.com/questions/22219004/grouping-rows-in-list-in-pandas-groupby

  • Hi Ernesto. Thanks for the answer. The submitted topic is different because it takes the data groups in list. And what I need to do is the opposite; take what’s on a list and add.

  • The code I’m using is pretty simple, so I didn’t think it made much sense to put it, but here it is: qtdgeneroyearv2 = pd.Dataframe(dataframefilms) qtdgeneroyearv2[['genres', 'year', 'votes']]. groupby(['year', 'genres']). sum() Hence I get : unhashable type: 'list'

1 answer

1


You can use the method explodes () from pandas 0.25.0 , for your case:

qtdgeneroyearv2.explode('genres') 

applying the explode and then grouping:

qtdgeneroyearv2.explode('genres')[['genres', 'year', 'votes']].groupby(['year', 'genres']).sum()

exit:

year  genres           
2016  Family      votes      25
      Game-Show   votes      25
      Music       votes      25
      Reality-TV  votes      25
2018  Comedy      votes    None
      Drama       votes      39
2019  Comedy      votes      16
2020  Comedy      votes    None
dtype: object
  • 1

    IT WORKED FRIEND! You burst me of joy here hahaha. Thank you so much

Browser other questions tagged

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