3

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 2

2

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]]
Sign up to request clarification or add additional context in comments.

11 Comments

Tried it but it results in an array of the list, for example, array([list([3.7, 1.5]), list([9.7, 2.9]), list([-1.2, 0.8]))] and that's where the normalizer.fit_transform() throws an error.
@YashGhorpade - With sample data? Or with real data? Because if real data and some groups has 2 or more like 2 values here it is possible.
With real data. I checked the length of each list within the array, it is same. Still throws this error, ValueError: setting an array element with a sequence.
One idea L = df.groupby(['tag'], sort=False).value.apply(list).tolist() and then print ([x for x in L if len(x!=2)]) return empty list?
Yup, it does. It's weird but this hack worked, np.array([i for i in arr]). When I passed this new array to Normalizer, it worked. But there could be some efficient way to it, right?
|
-1
df.groupby('tag')['value'].agg(lambda x: x.tolist()).values

3 Comments

This does not create numpy arrays but one numpy array containing lists.
OP did not ask for numpy arrays but for numpy array.
Nonetheless, the expected output from OP is not an array containing lists but one two-dimensional array (which could be considered one array of multiple arrays).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.