2017-04-04 142 views
4

矢量我有使用熊貓一個數據幀:如何提取GROUPBY大熊貓蟒蛇

one two three 

1  2 1 
4  1 1 
2  2 1 
3  1 2 
20  2 2 

現在,我將通過分組「三」提取的向量。 基本上,我應該基於分組「三」從「兩」列得到向量:

groupby('three') 
a=[2,1,2] 
b=[1,2] 

非常感謝

+0

重複數據刪除:https://stackoverflow.com/questions/22219004/grouping-rows-in-list-in-pandas-groupby – EdChum

回答

4

您可以使用groupby

s = df.groupby('three')['two'].apply(list) 
print (s) 
three 
1 [2, 1, 2] 
2  [1, 2] 
Name: two, dtype: object 

a = s.loc[1] 
b = s.loc[2] 
print (a) 
[2, 1, 2] 

print (b) 
[1, 2] 

如果需要嵌套的列表:

L = df.groupby('three')['two'].apply(list).tolist() 
print (L) 
[[2, 1, 2], [1, 2]] 

另一種可能的解決方案:

L = [list(x) for i, x in df.groupby('three')['two']] 
print (L) 
[[2, 1, 2], [1, 2]] 

L = [x.tolist() for i, x in tuple(df.groupby('three')['two'])] 
print (L) 
[[2, 1, 2], [1, 2]] 
+0

完美的,偉大的。但是,如何使用結果,它是一個DataFrame?基本上,我如何管理結果載體? – user7311536

+1

這意味着什麼?輸出爲['Series'](http://pandas.pydata.org/pandas-docs/stable/dsintro.html#series) – jezrael

+0

非常感謝。我把輸出放在DataFrame的列內,現在我要用plot.box來繪製我們已經獲得的數組,你能幫我嗎?獲得一個陰謀作爲一個盒子劇情序列 – user7311536