Pandas Using Unique row value as columns like pivot

Viewed 25

dataset: top 50 novels sold each years Genre column: fiction , nonfiction (only two unique values)

how can I summarize data so that I get a table of author name, and the number of fiction And nonfiction books they have written in two different columns ?

Here is the minimized version of dataset:

"""{'Name': {0: '10-Day Green Smoothie Cleanse', 1: '11/22/63: A Novel', 2: '12 Rules for Life: An Antidote to Chaos'},

'Author': {0: 'JJ Smith', 1: 'Stephen King', 2: 'Jordan B. Peterson'},

'User Rating': {0: 4.7, 1: 4.6, 2: 4.7},

'Reviews': {0: '17,350', 1: '2,052', 2: '18,979'},

'Price': {0: '$8.00', 1: '$22.00', 2: '$15.00'},

'Price_r': {0: '$8', 1: '$22', 2: '$15'},

'Year': {0: 2016, 1: 2011, 2: 2018},

'Genre': {0: 'Non Fiction', 1: 'Fiction', 2: 'Non Fiction'}} """

df.groupby(['Author']).Genre.value_counts().sort_values(ascending  =  False)

I have tried using group by but not getting sperate columns for fiction and non fiction.

1 Answers

We dont have the column's names but from what I understand, something like this should do the work :

df.groupby(["author", "genre"]).count()

Or (to get back the "author" and "genre" as columns instead of having them in the index) :

df.groupby(["author", "genre"]).count().reset_index()
Related