Converting pandas groupby values to numpy array

Viewed 1947

I tried multiple solutions but none of them gives the desired output.

I have a DataFrame:

 tag    value
 'A'     3.7
 'A'     1.5
 'E'     9.7
 'E'     2.9
 'B'    -1.2
 'B'     0.8

My expected output is a Numpy Array:

array([[3.7, 1.5],
      [9.7, 2.9],
      [-1.2, 0.8]])

I tried using groupby and converting in numpy array

df.groupby(['tag']).value.apply(np.array).values

But I get output as:

array([array([3.7, 1.5]), array([9.7, 2.9]), array([-1.2, 0.8]))], dtype=object)
2 Answers

If there is always same number of values per groups is possible create nested lists and pass to np.array, also for same order of groups add sort=False parameter to DataFrame.groupby:

arr = np.array(df.groupby(['tag'], sort=False).value.apply(list).tolist())
print (arr)
[[ 3.7  1.5]
 [ 9.7  2.9]
 [-1.2  0.8]]
df.groupby('tag')['value'].agg(lambda x: x.tolist()).values
Related