Pivoting a Pandas Dataframe containing strings - 'No numeric types to aggregate' error

前端 未结 2 2078
有刺的猬
有刺的猬 2020-12-01 11:09

There is a good number of questions about this error, but after looking around I\'m still not able to find/wrap my mind around a solution yet. I\'m trying to pivot a data fr

2条回答
  •  旧时难觅i
    2020-12-01 11:48

    There are several ways.

    1

    df1 = df.groupby(["id","contact_id","Network_Name","question"])['response_answer'].aggregate(lambda x: x).unstack().reset_index()
    df1.columns=df1.columns.tolist()
    print (df1)
    

    2

    df1 = df.set_index(["id","contact_id","Network_Name","question"])['response_answer'].unstack().reset_index()
    df1.columns=df1.columns.tolist()
    print (df1)
    

    3

    df1 = df.groupby(["id","contact_id","Network_Name","question"])['response_answer'].aggregate('first').unstack().reset_index()
    df1.columns=df1.columns.tolist()
    print (df1)
    

    4

    df1 = df.pivot_table(index=["id","contact_id","Network_Name"], columns='question', values=['response_answer'], aggfunc='first')
    df1.columns = df1.columns.droplevel()
    df1 = df1.reset_index()
    df1.columns=df1.columns.tolist()
    print (df1)
    

    Same ans.

        id  contact_id  Network_Name       City State Trip_End_Location
    0   16      137519          2206       None    Ca              None
    1   17      137520          2206       None    Ca              None
    2   18      137521          2206       None    Ca              None
    3   19      137522          2206       None    Ca              None
    4   20      137523          2208  Lancaster  None              None
    5   21      137524          2208  Lancaster  None              None
    6   22      137525          2208  Lancaster  None              None
    7   23      137526          2208  Lancaster  None              None
    8   24      137527          2208       None  None              Home
    9   25      137528          2208       None  None              Home
    10  26      137529          2208       None  None              Home
    11  27      137530          2208       None  None              Home
    

提交回复
热议问题