Home > OS >  Groupby and get the values in one dataframe
Groupby and get the values in one dataframe

Time:12-28

I have a dataframe which I need to do groupby by multiple columns and get the items within every group as a row;

enter image description here

I need to output a below table after group;

enter image description here

I have been looking for the answer but I was not able to find any, I appreciate if you can help we with the code.

CodePudding user response:

You could try this:

import pandas as pd

df = pd.read_csv('data.csv')
groups = ['group1', 'group2', 'group3']
df = df.groupby(groups).apply(lambda a: a.drop(groups, axis=1)[:])

print(df)

Output:

                        itemNo itemName
group1 group2 group3
A      AA     AAA    0    4412      xxx
                     3    9812      yhk
       C      CC     4    4431      alk
B      AA     BB     1    3456      xsc
                     2    4566      thg
  • Related