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]]
CodePudding user response:
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.
