How to plot the number of digits appearing in each index in a column as a function of the index in this column?

Viewed 23

Let say I have this dataframe :

 A         B   
 1       1401     
 1       1401     
 1       1501     
 2       1601     
 2       1601     
 3       1901     
 3       2001     
...      ...     
 n 

I would like to plot the number of digits appearing in each index in column A as a function of the index in column A. For example the output will be:

x = [1, 2, 3, ..., n]
y = [2, 1, 2] (when the same number appears several times (1401 or 1601 for example), we count it only once)

And then plot this as an histogram.

Thanks !

1 Answers

You can aggregate with nunique, then plot.bar:

df.groupby('A')['B'].nunique().plot.bar()

output:

enter image description here

With seaborn:

import seaborn as sns
sns.barplot(data=df, x='A', y='B', estimator=lambda x: len(set(x)), ci=None)

output:

enter image description here

Related