[英]Want to create column with lists of unique values using groupby and transform
這是一個樣本數據集
test = pd.DataFrame({
'a' : [1, 2, 3]*2,
'b' : ['a', 'a', 'b', 'b', 'b', 'b',],
'c' : [123, 456, 456, 123, 456, 123]
})
print(test)
a b c
0 1 a 123
1 2 a 456
2 3 b 456
3 1 b 123
4 2 b 456
5 3 b 123
如果我groupby
列'a'
和'b'
,然后嘗試獲得唯一值(名單'c'
)各組,預期結果使用我沒有得到transform
# using transform
print(test.groupby([
'a',
'b',
]).c.transform(pd.Series.unique))
0 123
1 456
2 456
3 123
4 456
5 123
如果我改用unique
,我幾乎可以得到預期的輸出:
# almost expected output
print(test.groupby([
'a',
'b',
]).c.unique())
a b
1 a [123]
b [123]
2 a [456]
b [456]
3 b [456, 123]
Name: c, dtype: object
我所希望的是使用transform
看起來像這樣的pd.Series
:
0 [123]
1 [456]
2 [456, 123]
3 [123]
4 [456]
5 [456, 123]
dtype: object
我知道我可以使用transform
來獲得'c'
的nunique
值,作為一系列這樣做:
print(test.groupby([
'a',
'b',
]).c.transform(pd.Series.nunique))
0 1
1 1
2 2
3 1
4 1
5 2
Name: c, dtype: int64
為什么我不能對unique
和transform
做類似的事情?
我知道我可以進行groupby
和unique
,然后進行reset_index
並與原始數據merge
,但是我希望有一個對pythonic / pandas更友好的方法。
我也嘗試使用set
和transform
,但是返回了錯誤。
print(test.groupby([
'a',
'b',
]).c.transform(set))
TypeError: 'set' type is unordered
是否
test.groupby(['a','b'])['c'].transform('unique')
為你工作?
輸出:
0 [123]
1 [456]
2 [456, 123]
3 [123]
4 [456]
5 [456, 123]
Name: c, dtype: object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.