在Pandas数据帧中打印唯一值

4
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]))

以上代码将打印每个列中唯一值的计数。我想要仅打印'object'类型列的唯一值计数。

是否有方法可以仅过滤“object”列?


1
你需要在这里检查:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html - MattR
3个回答

5

你可以像@JulianCienfuegos已经提到的那样,结合使用nunique()select_dtypes()

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

正如@root在以Pandas 0.20.0开头的评论中添加的那样,现在应该可以使用DataFrame.nunique()

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

2
作为对未来读者的提醒,DataFrame.nunique 将在版本0.20.0中可用,因此不需要使用apply - root

3

使用df.dtypes

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

b    3
c    3
dtype: int64


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接