pythonpandasdataframenumpyreform

python : reform multiple columns into two columns


I would like to reform the following dataframe

main data

into :

reformed data

Could somebody help me with that, please?


Solution

  • A screenshot is not a good format for community to reproduce your code, and data.

    That is a shape(m, n) to shape(u, v) problem, probably you don't know the term in Pandas, Numpy, but still can trynna google "reform", or "reshape".

    import pandas as pd
    import numpy as np
    df.shape
    ###
    (9, 12)
    

    enter image description here



    We can use np.hsplit() and np.vstack() to deal with,

    shape calculation: (9 × 12) = c×(9 × n), with n = 2

    # expected output columns  
    n = 2
    
    output = np.vstack(np.hsplit(df.values, df.shape[1]/n))
    output_df = pd.DataFrame(output, columns=['node1','node2'])
    print(output_df.head(10))
    ###
       node1  node2
    0  38.47  37.86
    1  37.63  37.02
    2  38.27  37.66
    3  38.64  38.03
    4  38.12  37.51
    5  37.57  36.96
    6  37.83  37.22
    7  37.62  37.01
    8  37.04  36.43
    9  40.17  39.52