How to make the columns values to indexes and then count the frequency in multiple other columns

Viewed 35

So I have the following data:

data = pd.DataFrame({'First' : ['a', 'b', 'b', 'c','a','d','d','d','c'], 'Second' : ['a','c','c','c','c','d','d','b','b'],'Third' : ['a','a','d','d','d','d','d','b','b']})

I want to make the values of column "First" (which are the same for column "Second" and "Third" ) as indexes and count the frequencies of those values in each column, in order to do a stacked bar plot. I also want to display the frequencies in the stacked bar plot as percentages, but that's another problem.

I tried to group somehow the data and then count the values or size but I don't seem to figure it out. Here is what I tried:

#some how grouby
choices=dfg['First']
dfg['Choices']=choices
dfg.head()
dfg=dfg.groupby(['Choices'])['First','Second Choice','Third Choice']

#value counts
dfg['First'].value_counts()

#size value
dfg= dfg.groupby(['First', 'Second Choice']).size()
dfg

If someone had any suggestions I would appreciate it very much!

1 Answers

I think you need counts values per columns:

df = data.apply(pd.value_counts)
print (df)
   First  Second  Third
a      2       1    2.0
b      2       2    2.0
c      2       4    NaN
d      3       2    5.0

and then ploting by DataFrame.plot.bar:

df.plot.bar()
Related