簡體   English   中英

想要使用groupby和transform創建包含唯一值列表的列

[英]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

為什么我不能對uniquetransform做類似的事情?

邊注

我知道我可以進行groupbyunique ,然后進行reset_index並與原始數據merge ,但是我希望有一個對pythonic / pandas更友好的方法。

我也嘗試使用settransform ,但是返回了錯誤。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM