Joan
Joan

Reputation: 31

Group panda values by unique values of another column

I have the following panda dataframe:

df = pd.DataFrame({'trial_time': ['0', '0',
                              '1', '1'],
                   'Max Speed': [1., 2, 3, 4]})

I want to create a dataframe that would for each unique value in trial_time bin/grab the corresponding values in an array. So 0 -> [1,2] 1 -> [3,4]

I read through pandas groupby documentation, but I'm still a bit stuck...

Upvotes: 1

Views: 894

Answers (1)

ouroboros1
ouroboros1

Reputation: 14459

You could use the following code:

s = df.groupby('trial_time')['Max Speed'].apply(lambda x: list(x))
print(s)

trial_time
0    [1.0, 2.0]
1    [3.0, 4.0]
Name: Max Speed, dtype: object

So, this will return a pd.Series with the unique values from trial_time as the index, and the corresponding lists as data.

Upvotes: 1

Related Questions