I have this dataframe
x = pd.DataFrame.from_dict({'cat1':['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C'], 'cat2':['X', 'X', 'Y', 'Y', 'Y', 'Y', 'Z', 'Z']})
cat1 cat2
0 A X
1 A X
2 A Y
3 B Y
4 B Y
5 C Y
6 C Z
7 C Z
I want to group by cat1
, and then aggregate cat2
as sets of different values, such as
cat1 cat2
0 A (X, Y)
1 B (Y,)
2 C (Y, Z)
This is part of a bigger dataframe with more columns, each of which has its own aggregation function, so how do I pass this functionality to the aggregation dictionary?
Or we can filter the dataframe before groupby
This first groups the entire dataframe by 'cat1', selects only the series 'cat2', and reduces each group to the unique set of 'cat2' values. The result puts the 'cat1' values in the index, so reset_index() will pull those values back out as a column if you need it in that format.
Output
Use lambda function with
set
orunique
, also convert output totuple
s:Or:
EDIT:
If there is only one
lambda
function or no problem with column name<lambda>
:Groupby and unique gives you unique values
If you want to have the output in tuple, try