gpt4 book ai didi

Pandas:将复数列转换为模数和参数列

转载 作者:行者123 更新时间:2023-12-04 08:12:00 26 4
gpt4 key购买 nike

情况
考虑以下包含复数的示例数据帧:

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)
在控制台输出中如下所示:
                    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
问题
我想将每一列转换为两列:一列是复数的模数,一列是复数的参数(以度为单位)。所需的结果数据框如下所示:
         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
我将如何能够实现这一目标?

最佳答案

尝试:

df.agg([np.abs, np.angle])
输出(参数是辐射式的,您可以轻松转换为度数)
          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
或者您可以手动使用 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)
输出:
         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

关于Pandas:将复数列转换为模数和参数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65907736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com