如何从 python 中具有实数的数据帧制作包含复数的数据帧?

How to make a dataframe containing complex numbers from dataframes with real numbers in python?

在 python 中,我有一个包含 2 列实数的数据框。我想制作复数并将这两列用作我的新数据集的实部和虚部。我已经尝试 complex(df['wspd'].astype(float),df['wdir'].astype(float)) 但我仍然收到此错误:

cannot convert the series to <class 'float'>

我怎样才能实现它?

函数complex只能处理标量。可以将第二列转为虚乘1j,然后求和:

df['wspd'] + df['wdir'] * 1j

示例:

df = pd.DataFrame({'wspd':[10.23,2.4,30.6], 'wdir':[2.3,7.8,4]})
df['com'] = df['wspd'] + df['wdir'] * 1j
print (df)
    wspd  wdir           com
0  10.23   2.3  (10.23+2.3j)
1   2.40   7.8    (2.4+7.8j)
2  30.60   4.0     (30.6+4j)

另一种方法是通过这种方式从 df 创建一个新数据框 df2

df2 = pd.DataFrame([complex(i.wspd, i.wdir) for i in df.iloc], index=df.index)

Dataframes 的 .iloc(基于 int 的索引)和 .loc(基于标签的索引)对象属性是可迭代的,因此可以以这种方式使用。

python 原生复杂函数的替代方法是使用 numpy.complex,我不确定哪个更快,可能是 numpy 函数,因为 pandas 继承了 numpy 的数据类型.