Consider the following example dataframe containing complex numbers:
data = [
[np.complex(+1.15208050, -2.48857386), np.complex(-0.85295162, +0.10011025), np.complex(-0.61440517, -1.15813006)],
[np.complex(-1.36170542, -0.78118157), np.complex(+1.10912405, +0.87261775), np.complex(-0.55295896, +1.34406899)],
[np.complex(-0.19407632, -0.61834442), np.complex(-0.14378835, +1.11290952), np.complex(-1.17956510, -0.47438966)],
[np.complex(-0.09920323, -0.34497172), np.complex(-0.16600567, +0.81955786), np.complex(-1.54853844, -0.54138271)],
[np.complex(-0.28935140, +0.10951172), np.complex(-1.32314178, -0.05319875), np.complex(-1.08771716, -1.09595183)],
]
columns = ["A", "B", "C"]
df = pd.DataFrame(data, columns=columns)
which looks as follows in console output:
A B C
0 1.152081-2.488574j -0.852952+0.100110j -0.614405-1.158130j
1 -1.361705-0.781182j 1.109124+0.872618j -0.552959+1.344069j
2 -0.194076-0.618344j -0.143788+1.112910j -1.179565-0.474390j
3 -0.099203-0.344972j -0.166006+0.819558j -1.548538-0.541383j
4 -0.289351+0.109512j -1.323142-0.053199j -1.087717-1.095952j
I would like to transform each column into two columns: one column with the modulus of the complex numbers, and one column with the argument of the complex numbers (in degrees). The desired result dataframe would look like this:
A1 A2 B1 B2 C1 C2
0 2.742315 -65.158313 0.858806 173.305866 1.311014 -117.946614
1 1.569868 -150.158019 1.411247 38.194359 1.453370 112.362593
2 0.648086 -107.425218 1.122160 97.361855 1.271385 -158.091322
3 0.358952 -106.043604 0.836202 101.450632 1.640447 -160.729923
4 0.309382 159.269694 1.324211 -177.697584 1.544098 -134.783937
How would I be able to achieve this?
Try:
df.agg([np.abs, np.angle])
Output (argument is in radiant, you can convert to degree easily)
A B C
absolute angle absolute angle absolute angle
0 2.742315 -1.137227 0.858806 3.024758 1.311014 -2.058557
1 1.569868 -2.620752 1.411247 0.666617 1.453370 1.961097
2 0.648086 -1.874924 1.122160 1.699285 1.271385 -2.759214
3 0.358952 -1.850810 0.836202 1.770648 1.640447 -2.805266
4 0.309382 2.779781 1.324211 -3.101408 1.544098 -2.352423
Or you can do manually with pd.concat
:
pd.concat([df.apply(np.abs).add_suffix(1),
df.apply(np.angle, deg=True).add_suffix(2)
], axis=1
).sort_index(axis=1)
Output:
A1 A2 B1 B2 C1 C2
0 2.742315 -65.158313 0.858806 173.305866 1.311014 -117.946614
1 1.569868 -150.158019 1.411247 38.194359 1.453370 112.362593
2 0.648086 -107.425218 1.122160 97.361855 1.271385 -158.091322
3 0.358952 -106.043604 0.836202 101.450632 1.640447 -160.729923
4 0.309382 159.269694 1.324211 -177.697584 1.544098 -134.783937