简体   繁体   中英

Advanced pandas value_counts() with matplotlib plotting

I have a website I manage and I have been applying data analytics with Pandas to get useful insights from my products and the companies that supply them.

Now on my website, there are tons of products there and I give each product an ID to identify each product that is produced by a Company, so that means a Company can have different products ie. productIDs.

On my site, you can compare products that meet your demands from different companies and I programmed my site to allow only three comparisons. You can only compare three products with various features at a time.

I have been able to setup google analytics to track the data. so for example with a diagram below: A customer compared product IDs 920 with 470 and 212 side by side.

在此处输入图片说明

I would like to perform value_counts independently for each product and then see which products were compared the most versus other products and have a Seaborn or matplotlib Group bar plot like this?

在此处输入图片说明

Here is the dataframe for your convenience:

df = pd.DataFrame({'ProductID_A': ['920','162','920','920','920','165','920'],
 'ProductID_B': ['470','470','470','212', np.nan,'470','470'],
 'ProductID_C': ['212','212',"212", "570",'212','1670', '212']})

Thanks for your time.

Does this achieve your desired result?

df. unstack df. unstack pivots the original dataframe then reset_index is used to convert everything so it is not grouped anymore. The column names in the groupby are the default left from unstack but that could be changed or specified in your plot.

df1 = pd.DataFrame(df.unstack()).reset_index()

df2 = df1[[0, 'level_0']].groupby(0).count()

sns.barplot(x= df2.index, y = 'level_0', data = df2)
plt.ylabel('count')
plt.xlabel('product ID')

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM