import pandas as pd
df = pd.DataFrame({'a':[1,2,3,4],'b':['a','b','d','d'],'c':['v','v','g','w']})
print(df.apply(lambda x: x.unique().shape[0]))
above code will print count of unique values in each columns. I want to print count of unique values only for columns of 'object' type.
is there any way to filter only 'object' columns
You can use select_dtypes()
as @JulianCienfuegos has already said in conjunction with nunique():
In [9]: df.select_dtypes(include=['object']).apply(lambda x: x.nunique())
Out[9]:
b 3
c 3
dtype: int64
As @root has added in the comment starting with Pandas 0.20.0 it should be possible to use DataFrame.nunique()
:
df.select_dtypes(include=['object']).nunique()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With