2017-03-14 53 views
1

我有以下的數據幀my_df大熊貓:聚合的列來創建一個非重複序列

name timestamp  color 
--------------------------- 
John 2017-01-01 blue 
John 2017-01-02 blue 
John 2017-01-03 blue 
John 2017-01-04 yellow 
John 2017-01-05 red 
John 2017-01-06 red 
Ann  2017-01-04 green 
Ann  2017-01-05 orange 
Ann  2017-01-06 orange 
Ann  2017-01-07 red 
Ann  2017-01-08 black 
Dan  2017-01-11 blue 
Dan  2017-01-12 blue 
Dan  2017-01-13 green 
Dan  2017-01-14 yellow 

我然後使用以下代碼來找到每個人的顏色序列:

new_df = my_df.groupby(['name'], as_index=False).color \ 
    .agg({"color_list": lambda x: list(x)}) 

然後new_df樣子:

name  color_list 
    ----------------------------------------------- 
    John  blue, blue, blue, yellow, red, red 
    Ann   green, orange, orange,red, black 
    Dan   blue, blue, green, yellow 

但是,如果我想要創建一個color_seq(沒有後綴重複的顏色)而不是像下面的color_list,我該如何修改我的上面的代碼?謝謝!

name  color_seq 
    ----------------------------------------------- 
    John  blue, yellow, red 
    Ann   green, orange, red, black 
    Dan   blue, green, yellow 
+0

拉姆達X:集(x)的? – Vaishali

+0

不,設置不能保證順序的順序。 – Edamame

回答

1

如果您允許非連續重複,則必須仔細過濾。 的一種方式做到這一點:

def filter(l): 
    l.append(None) 
    return ','.join([x for (i,x) in enumerate (l[:-1]) 
    if l[i] != l[i+1]]) 

out=df.groupby('name')['color'].apply(list).apply(filter) 

name 
Ann  green,orange,red,black 
Dan   blue,green,yellow 
John   blue,yellow,red 
Name: color, dtype: object 
+0

謝謝!但我需要輸出爲數據幀格式,結果作爲數據幀中的新列,而不僅僅是在屏幕上打印。那可能嗎? – Edamame

+0

Ok.I通過在.agg({「color_list」:lambda x:the_filter(list(x))}}中使用過濾器來獲得它的效果。謝謝!你能否解釋一下關於枚舉(l [: - 1])中的「x for(i,x)」是什麼意思?謝謝! – Edamame