Pandas, Create Columns After Groupby
Regarding the Pandas DataFrame 'test_df': id_customer id_order product_name 3 78 product1 3 79 product2 3 80
Solution 1:
Note: I recommend using head to do this rather than using multiple columns:
In [11]: g = df.groupby('id_customer')
In [12]: g.head(2)
Out[12]:
id_customer id_order product_name
0378 product1
1379 product2
37100 product4
49109 product5
You can combine the 0th and 1st using nth and then concat these:
In [21]: g = df.groupby('id_customer')
In [22]: g[['id_order', 'product_name']].nth(0)
Out[22]:
id_order product_name
id_customer
378 product1
7100 product4
9109 product5
In [23]: g[['id_order', 'product_name']].nth(1)
Out[23]:
id_order product_name
id_customer
379 product2
In [24]: a = g[['id_order', 'product_name']].nth(0)
b = g[['id_order', 'product_name']].nth(1)
In [25]: pd.concat([a, b], axis=1)
Out[25]:
id_order product_name id_order product_name
id_customer
378 product1 79 product2
7100 product4 NaN NaN
9109 product5 NaN NaN
Post a Comment for "Pandas, Create Columns After Groupby"