python - Modify matrix df format -


having df as:

    14       15         16 14  10.1166  18.2331    65.0185 15  18.2331  6.664      57.5195 16  65.3499  57.851     20.9907 

what different more efficient way modify df as

     b   c 0  14  14  10.1166 1  14  15  18.2331 2  14  16  65.0185 3  15  14  18.2331 4  15  15  6.664  etc. 

i wrote code, dont fact need use loop it.

for row in tt.index:     row_vals = tt[tt.index==row]     col_vals = row_vals.t     col_vals['from_zone'] = row     col_vals['to_zone'] = tt.index     col_vals['travel_time'] = col_vals[row].astype('int')     col_vals = col_vals.drop(row, axis=1)     travel_data = pd.concat([travel_data,col_vals]) 

in [58]: df.stack().reset_index().rename(columns={'level_0':'a','level_1':'b',0:'c'}) out[58]:       b        c 0  14  14  10.1166 1  14  15  18.2331 2  14  16  65.0185 3  15  14  18.2331 4  15  15   6.6640 5  15  16  57.5195 6  16  14  65.3499 7  16  15  57.8510 8  16  16  20.9907 

step step:

in [59]: df.stack() out[59]: 14  14    10.1166     15    18.2331     16    65.0185 15  14    18.2331     15     6.6640     16    57.5195 16  14    65.3499     15    57.8510     16    20.9907 dtype: float64  in [60]: df.stack().reset_index() out[60]:    level_0 level_1        0 0       14      14  10.1166 1       14      15  18.2331 2       14      16  65.0185 3       15      14  18.2331 4       15      15   6.6640 5       15      16  57.5195 6       16      14  65.3499 7       16      15  57.8510 8       16      16  20.9907 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -