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

后端 未结 3 1816
忘掉有多难
忘掉有多难 2021-01-16 01:04

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

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-16 01:40

    Heres another solution using a list comp and df.duplicated with .loc for assignment.

    import numpy as np
    df = pd.read_excel(file,sheet_name=yoursheet)
    
    #order the months. 
    
    df['Month'] = pd.Categorical(df['Month'],
                   pd.to_datetime(df['Month'],format='%b').drop_duplicates().sort_values().dt.strftime('%b'))
    
    
    
    df = df.sort_values(['Month']).reset_index(drop=True)
    
    df1 = pd.concat([data.append(data.iloc[0]) for name,data in df.groupby('Name')])
    
    df1.loc[df1.duplicated(keep='last'),1:] = ''
    
    df1['Name'] = np.where(df1['Month'].ne(''),df1['Month'],df1['Name'])
    
    final = df1.drop('Month',1)
    

       Name ID Shift
    0   Jon         
    3   Jan  1     A
    4   Feb  1     A
    5   Feb  1     C
    6   Mar  1     C
    0   Jan  1     B
    1  Mike         
    2   Jan  1     B
    1   Jan  1     A
    

提交回复
热议问题