Search code examples
pythonpandasdataframecomplex-numbers

Modify dataframe with complex values into a new multiindexed dataframe with real and imaginary parts using pandas


I have a dataframe with complex numbers as shown below,

>>>df.head()
         96               98
1   3.608719+23.596415j 3.782185+22.818022j
2   7.239342+28.990936j 6.801471+26.978671j
3   3.671441+23.73544j  3.842973+22.940337j
4   3.935188+24.191112j 4.063692+23.269834j
5   3.544675+23.561207j 3.852818+22.951067j

I am trying to create a new multiindexed dataframe out of it as below,

             96                     98  
       R           X           R           X
1   3.608719    23.596415   3.782185    22.818022
2   7.239342    28.990936   6.801471    26.978671
3   3.671441    23.73544    3.842973    22.940337
4   3.935188    24.191112   4.063692    23.269834
5   3.544675    23.561207   3.852818    22.951067

I have tried splitting them into real & imaginary dataframes and then merge/concat them, but was not successful.


Solution

  • You can use:

    df = pd.concat([df.apply(lambda x: x.real), df.apply(lambda x: x.imag)], 
                   axis=1, 
                   keys=('R','X')) \
           .swaplevel(0,1,1) \
           .sort_index(1)
    print (df)
             96                   98           
              R          X         R          X
    1  3.608719  23.596415  3.782185  22.818022
    2  7.239342  28.990936  6.801471  26.978671
    3  3.671441  23.735440  3.842973  22.940337
    4  3.935188  24.191112  4.063692  23.269834
    5  3.544675  23.561207  3.852818  22.951067
    

    Another solution:

    a = df.values
    mux = pd.MultiIndex.from_product([ ['R','X'], df.columns])
    df1 = pd.DataFrame(np.concatenate([a.real, a.imag], axis=1), columns=mux)
            .swaplevel(0,1,1)
            .sort_index(1)
    print (df1)
             96                   98           
              R          X         R          X
    0  3.608719  23.596415  3.782185  22.818022
    1  7.239342  28.990936  6.801471  26.978671
    2  3.671441  23.735440  3.842973  22.940337
    3  3.935188  24.191112  4.063692  23.269834
    4  3.544675  23.561207  3.852818  22.951067