Search code examples
pythonpython-3.xpandaspandas-groupbyvscode-python

how to crate the group by in pandas only in one level


I am importing below df3 dataframe in my excel file and want to grouby only Name and rest dublicate data should reflect as below .

Note (Each Month data will be added as per month wise. )

Df3 =pd.read_Excel('Data')
print (df3)      

Name    ID  Month   Shift

Jon     1   Feb     A
Jon     1   Jan     B
Jon     1   Mar     C
Mike    1   Jan     A
Mike    1   Jan     B
Jon     1   Feb     C
Jon     1   Jan     A

enter image description here

and i want to have output like as below in the same formate . Please help me on same as im stuck here .

enter image description here

Will be greatfull for help and support .


Solution

  • You can achieve it by

    df=df.iloc[pd.to_datetime(df.Month,format='%b').argsort()]
    df=pd.concat([pd.DataFrame({'Month':[x] }).append(y).fillna('').append(pd.DataFrame(dict.fromkeys(y.columns,['']))) for x , y in df.groupby('Name')]).drop('Name',1).iloc[:-1]
    

    print(df)
    
     Month ID Shift
    0   Jon         
    1   Jan  1     B
    6   Jan  1     A
    0   Feb  1     A
    5   Feb  1     C
    2   Mar  1     C
    0               
    0  Mike         
    3   Jan  1     A
    4   Jan  1     B