Convert a python dataframe with multiple rows into one row using python pandas?

后端 未结 2 2105
南笙
南笙 2021-02-10 11:17

Having the following dataframe,

df = pd.DataFrame({\'device_id\' : [\'0\',\'0\',\'1\',\'1\',\'2\',\'2\'],
               \'p_food\'    : [0.2,0.1,0.3,0.5,0.1,0.7         


        
相关标签:
2条回答
  • 2021-02-10 11:41
    df_m = df.drop_duplicates('device_id', keep='first')\
             .merge(df, on='device_id')\
             .drop_duplicates('device_id', keep='last')\
             [['device_id', 'p_food_x', 'p_food_y', 'p_phone_x', 'p_phone_y']]\
             .reset_index(drop=True)
    
    print(df_m)
    
      device_id  p_food_x  p_food_y  p_phone_x  p_phone_y
    0         0       0.2       0.1        0.8        0.9
    1         1       0.3       0.5        0.7        0.5
    2         2       0.1       0.7        0.9        0.3
    
    0 讨论(0)
  • 2021-02-10 11:49

    If you are still looking for an answer using groupby

    df = df.groupby('device_id')['p_food', 'p_phone'].apply(lambda x: pd.DataFrame(x.values)).unstack().reset_index()
    df.columns = df.columns.droplevel()
    df.columns = ['device_id','p_food_1', 'p_food_2', 'p_phone_1','p_phone_2']
    

    You get

        device_id   p_food_1    p_food_2    p_phone_1   p_phone_2
    0   0           0.2         0.1         0.8         0.9
    1   1           0.3         0.5         0.7         0.5
    2   2           0.1         0.7         0.9         0.3
    
    0 讨论(0)
提交回复
热议问题