Construct pandas DataFrame from list of tuples of (row,col,values)

后端 未结 3 1883
渐次进展
渐次进展 2020-12-04 09:44

I have a list of tuples like

data = [
(\'r1\', \'c1\', avg11, stdev11),
(\'r1\', \'c2\', avg12, stdev12),
(\'r2\', \'c1\', avg21, stdev21),
(\'r2\', \'c2\',          


        
3条回答
  •  -上瘾入骨i
    2020-12-04 10:00

    I submit that it is better to leave your data stacked as it is:

    df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])
    
    # Possibly also this if these can always be the indexes:
    # df = df.set_index(['R_Number', 'C_Number'])
    

    Then it's a bit more intuitive to say

    df.set_index(['R_Number', 'C_Number']).Avg.unstack(level=1)
    

    This way it is implicit that you're seeking to reshape the averages, or the standard deviations. Whereas, just using pivot, it's purely based on column convention as to what semantic entity it is that you are reshaping.

提交回复
热议问题