2017-03-17 77 views
3
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])) 

上面的代碼將打印每列中唯一值的計數。我只想打印「對象」類型的列的唯一值的計數。在熊貓數據框中打印唯一值

有什麼辦法僅過濾「對象」列

+1

你將要檢查[這裏](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html) – MattR

回答

4

您可以使用select_dtypes()@JulianCienfuegos已經結合nunique()說:

In [9]: df.select_dtypes(include=['object']).apply(lambda x: x.nunique()) 
Out[9]: 
b 3 
c 3 
dtype: int64 

由於@root在註釋中增加了開始大熊貓0.20.0應該儘可能使用DataFrame.nunique()

df.select_dtypes(include=['object']).nunique() 
+2

作爲一個音符未來的讀者,'DataFrame.nunique'將在0.20.0版本中可用,所以'apply'不需要。 – root

+0

@root,好點,謝謝!我不知道那個... – MaxU

3

使用df.dtypes

df.loc[:, df.dtypes == object].apply(pd.Series.nunique) 

b 3 
c 3 
dtype: int64