使用分组器列出唯一值 [英] List unique values using grouper
本文介绍了使用分组器列出唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,其中的索引是日期时间,列A和B是对象.我需要每周查看A和B的唯一值. 我设法获得了每周的唯一值计数(为此我正在使用pd.grouper函数),但是我正在努力获取每周的唯一值.
I have a dataframe in which the index is a datetime and column A and B are objects. I need to see the unique values of A and B per week. I managed to get the unique value count per week (I am using the pd.grouper function for that) but I am struggling to get the unique values per week.
这段代码为我提供了每周的唯一价值计数
This code gives me the unique value counts per week
df_unique = pd.DataFrame(df.groupby(pd.Grouper(freq="W"))['A', 'B'].nunique())
但是,下面的代码并不能为我提供每周的唯一值
However, the code below does not give me the unique values itself per week
df_unique_list = pd.DataFrame(df.groupby(pd.Grouper(freq="W"))['A', 'B'].unique())
此代码为我提供了以下错误消息
This code gives me te following error message
AttributeError: 'DataFrameGroupBy' object has no attribute 'unique'
推荐答案
Use lambda function with Series.unique
and converting to list:
np.random.seed(123)
rng = pd.date_range('2017-04-03', periods=20)
df = pd.DataFrame({'A': np.random.choice([1,2,3,4,5,6], size=20),
'B': np.random.choice([1,2,3,4,5,6,7,8], size=20)}, index=rng)
print (df)
A B
2017-04-03 6 1
2017-04-04 3 5
2017-04-05 5 2
2017-04-06 3 8
2017-04-07 2 4
2017-04-08 4 3
2017-04-09 3 5
2017-04-10 4 8
2017-04-11 2 3
2017-04-12 2 5
2017-04-13 1 8
2017-04-14 2 1
2017-04-15 2 6
2017-04-16 1 1
2017-04-17 1 8
2017-04-18 2 2
2017-04-19 4 4
2017-04-20 6 5
2017-04-21 5 5
2017-04-22 1 5
df_unique_list = df.groupby(pd.Grouper(freq="W"))['A', 'B'].agg(lambda x: list(x.unique()))
print (df_unique_list)
A B
2017-04-09 [6, 3, 5, 2, 4] [1, 5, 2, 8, 4, 3]
2017-04-16 [4, 2, 1] [8, 3, 5, 1, 6]
2017-04-23 [1, 2, 4, 6, 5] [8, 2, 4, 5]
这篇关于使用分组器列出唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文