1

I am beginner in python. I am just wondering, I have this data in a pandas dataframe

type value
A 1
A 4
A 3
B 6
B 2
B 2

where each type will have three value (it can be different value or same value)

and what I want is to create a list of list (or anything, I don't know the exact name since I'm stuck to search the similar question using this vocabulary) but group by type column

expected output is exactly list of list like this:

[[1,4,3],[6,2,2]]

1 Answer 1

2
df.groupby('type').agg(pd.Series.tolist)['value'].tolist()

or simply:

df.groupby('type').agg(list)['value'].tolist()

Edit:

It depends on whether which number do you want to sort upon.. in this case, it will sort on the first element of the list which is 1.

If you want to reverse you can simply say k = df.groupby('type').agg(list)['value'].tolist()

k.sort(reverse=True) 

it will give you [[6,2,2], [1,4,3]]. If you want to sort on any of the values of list you have to apply key=some_function() accordingly.

Sign up to request clarification or add additional context in comments.

1 Comment

thankyou! it really help. a question, let say i have 100 types (A, B, C, ...etc), how can I keep getting list of list but sort by type column? so in above case, I will definitely get [[1,4,3],[6,2,2]] instead of [[6,2,2], [1,4,3]]. I've tried df.sort_values(by=['type']).groupby('type').agg(list)['value'].tolist() but didn't work

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.