Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how extract a vector from groupby pandas in python

Tags:

python

pandas

I have a DataFrame using pandas:

one    two  three

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

Now, I would extract the a vector by grouping 'three'. Basically, I should obtain vectors from the 'two' column based on grouping "three":

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

thanks a lot

like image 379
user7311536 Avatar asked Apr 04 '17 14:04

user7311536


People also ask

What kind of object does Groupby return?

GroupBy objects are returned by groupby calls: pandas. DataFrame.


1 Answers

You can use 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]

If need nested lists:

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

Another possible solutions:

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]]
like image 181
jezrael Avatar answered Nov 04 '22 14:11

jezrael