7

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

user7311536
  • 137
  • 2
  • 8

1 Answers1

8

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]]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Perfect, great. But, how can i use the result, it is a DataFrame? basically, how can i manage the resulting vectors? – user7311536 Apr 04 '17 at 14:50
  • 1
    What does it mean manage? output is [`Series`](http://pandas.pydata.org/pandas-docs/stable/dsintro.html#series) – jezrael Apr 04 '17 at 14:52
  • Thank a lot. I have putted the output within columns in a DataFrame, now I would plot with plot.box just the arrays that we have obtained, could you please help me? Obtaining a plot as a sequence of box plot – user7311536 Apr 04 '17 at 15:11
  • Glad can help you, nice day! – jezrael Apr 04 '17 at 15:12
  • Thank a lot. I have putted the output within columns in a DataFrame, now I would plot with plot.box just the arrays that we have obtained, could you please help me? Obtaining a plot as a sequence of box plot – user7311536 Apr 04 '17 at 15:28
  • Now I am only on phone, so it is problematic answer. The best is check [this](http://pandas.pydata.org/pandas-docs/stable/visualization.html#box-plots), if still problem try ask another question. Dont forget add data sample, code what you try and describe desired output. – jezrael Apr 04 '17 at 16:58