A data-frame and I want to transform it.
JavaScript
x
6
1
data = {'Number': [536, 578, 36, 468, 86],
2
'Content' : ["Banana","Apple","Orange","Mango","Grape"],
3
'Quantity': [1, 2, 5, 2, 6],
4
'Origin': ["TX","TX","OP","OP","OP"]}
5
df = pd.DataFrame(data)
6
The ideal result is something like:
JavaScript
1
3
1
OP [[36,5,Orange], [86,6,Grape], [468,2,Mango]]
2
TX [[536,1,Banana], [578,2,Apple]]
3
I tried:
JavaScript
1
2
1
df.groupby(['Origin', 'Number', 'Quantity'])['Content'].apply(list))
2
also:
JavaScript
1
2
1
df.groupby(['Origin', 'Number', 'Quantity'])'Content'].apply(list)).groupby(level=0).apply(list)
2
But not getting nearer.
What’s the right way?
Advertisement
Answer
You can do:
JavaScript
1
2
1
df.groupby('Origin').apply(lambda x: x.drop('Origin', axis=1).values.tolist())
2
Output:
JavaScript
1
5
1
Origin
2
OP [[36, Orange, 5], [468, Mango, 2], [86, Grape,
3
TX [[536, Banana, 1], [578, Apple, 2]]
4
dtype: object
5
If you want the list in the correct order, you would need to re-order your columns. For example:
JavaScript
1
5
1
(df[['Number', 'Quantity', 'Content']]
2
.groupby(df['Origin'])
3
.apply(lambda x: x.values.tolist())
4
)
5
And you get:
JavaScript
1
5
1
Origin
2
OP [[36, 5, Orange], [468, 2, Mango], [86, 6, Gra
3
TX [[536, 1, Banana], [578, 2, Apple]]
4
dtype: object
5