Convert pandas dataframe to list of tuples - ('Row', 'Column', Value)

后端 未结 3 1528
谎友^
谎友^ 2021-01-07 12:17

There are a few other questions regarding the same subject, but the format desired is different in all.

I am trying to build a heatmap visualization using holoviews

3条回答
  •  灰色年华
    2021-01-07 13:12

    You can reshape first by stack and then convert to tuples:

    tups = [tuple(x) for x in df.stack().reset_index().values.tolist()]
    

    Another similar solution is create 3 levels MultiIndex:

    tups = df.stack().to_frame().set_index(0, append=True).index.tolist()
    

    Or zip 3 separately arrays with numpy.repeat, numpy.tile and ravel:

    a = np.repeat(df.index, len(df.columns))
    b = np.tile(df.columns, len(df))
    c = df.values.ravel()
    
    tups = list(zip(a,b,c))
    

提交回复
热议问题