I have a dataframe
:
JavaScript
x
7
1
order_creationdate orderid productid quantity prod_name price Amount
2
0 2021-01-18 22:27:03.341260 1 SnyTV 3.0 Sony LED TV 412.0 1236.0
3
1 2021-01-18 17:28:03.343089 1 AMDR5 1.0 AMD Ryzen 5 313.0 313.0
4
2 2021-01-18 13:19:03.343842 1 INTI0 8.0 Intel I10 146.0 1168.0
5
3 2021-01-18 10:24:03.344399 1 INTI0 5.0 Intel I10 146.0 730.0
6
4 2021-01-18 12:29:03.344880 1 CMCFN 4.0 coolermaster CPU FAN 675.0 2700.0
7
Index 2 and 3 have the same product id’s, hence its the same order, so i am trying to combine the rows into one single row, to get :
JavaScript
1
2
1
INTI0 13 .0 146.0 1898.0
2
the final df
being :
JavaScript
1
6
1
order_creationdate orderid productid quantity prod_name price Amount
2
0 2021-01-18 22:27:03.341260 1 SnyTV 3.0 Sony LED TV 412.0 1236.0
3
1 2021-01-18 17:28:03.343089 1 AMDR5 1.0 AMD Ryzen 5 313.0 313.0
4
2 2021-01-18 13:19:03.343842 1 INTI0 13.0 Intel I10 146.0 1898.0
5
3 2021-01-18 12:29:03.344880 1 CMCFN 4.0 coolermaster CPU FAN 675.0 2700.0
6
I have tried using df.groupby
function :
JavaScript
1
10
10
1
df2['productid'] =df2['productid'].astype('str')
2
3
arr = np.sort(df2[['productid','quantity']], axis=1)
4
5
df2 = (df2.groupby([arr[:, 0],arr[:, 1]])
6
.agg({'price':'sum', 'Amount':'sum'})
7
.rename_axis(('X','Y'))
8
.reset_index())
9
print(df2)
10
But it throws datatype error
JavaScript
1
7
1
File "/home/anti/Documents/db/create_rec.py", line 65, in <module>
2
arr = np.sort(df2[['productid','quantity']], axis=1)
3
File "<__array_function__ internals>", line 5, in sort
4
File "/home/anti/.local/lib/python3.8/site-packages/numpy/core/fromnumeric.py", line 991, in sort
5
a.sort(axis=axis, kind=kind, order=order)
6
TypeError: '<' not supported between instances of 'float' and 'str'
7
Advertisement
Answer
JavaScript
1
4
1
df2.groupby(['productid', 'orderid'], as_index=False).agg(
2
{'quantity': sum, 'Amount': sum, 'order_creationdate': min, 'prod_name': min, 'price': min}
3
)
4
The output is:
JavaScript
1
6
1
productid orderid quantity Amount order_creationdate prod_name price
2
0 AMDR5 1 1.0 313.0 2021-01-18 17:28:03.343089 AMD Ryzen 5 313.0
3
1 CMCFN 1 4.0 2700.0 2021-01-18 12:29:03.344880 coolermaster CPU FAN 675.0
4
2 INTI0 1 13.0 1898.0 2021-01-18 10:24:03.344399 Intel I10 146.0
5
3 SnyTV 1 3.0 1236.0 2021-01-18 22:27:03.341260 Sony LED TV 412.0
6