如何在包含複數的 Pandas Series 中計算絕對值?


Pandas Series 有一個方法可以計算 Series 元素的絕對值。此函式也可用於計算包含複數的 Series 的絕對值。

Pandas Series 中的 abs() 方法將返回一個新的 Series,其中包含已計算的包含複數的 Series 的絕對值。

複數的絕對值是 $\sqrt{a^{2}+b^{2}}$,其中 a 是複數的實部,b 是複數的虛部。

示例

# importing pandas packages
import pandas as pd


#creating a series with null data
s_obj = pd.Series([2.5 + 3j, -1 - 3.5j, 9 - 6j, 3 + 2j, 10 + 4j, -4 + 1j])

print(s_obj, end='

') #calculate absolute values result = s_obj.abs() #print the result print(result)

解釋

在下面的示例中,我們建立了一個包含複數的 Series。之後,我們計算了 Series s_obj 中每個複數的絕對值。

在我們的 Series 中,有一些正複數和負複數。我們可以在下面的輸出塊中看到每個複數的絕對值。

輸出

0   2.500000+3.000000j
1  -1.000000-3.500000j
2   9.000000-6.000000j
3   3.000000+2.000000j
4  10.000000+4.000000j
5  -4.000000+1.000000j
dtype: complex128

0   3.905125
1   3.640055
2  10.816654
3   3.605551
4  10.770330
5   4.123106
dtype: float64

在這個輸出塊中,我們有兩個 Series 物件,一個包含複數的 Series,另一個包含相應複數 Series 的絕對值。透過使用 Pandas Series 的 abs() 方法,我們計算了 Series 中每個複數的絕對值。

示例

# importing pandas packages
import pandas as pd

#creating a series with null data
s = pd.Series([-0.3 - 0.3j, 1.3 + 0.3j, 4.2 + 5.29j, -9.037-5.03j, 2.34+2.1j])

print(s, end='

') #calculate absolute values result = s.abs() #print the result print(result)

解釋

這是另一個計算包含複數的 Series 的絕對值的示例。最初,我們建立了一個包含複數的 Series 物件,然後計算了這些複數的絕對值。

輸出

0  -0.300000-0.300000j
1   1.300000+0.300000j
2   4.200000+5.290000j
3  -9.037000-5.030000j
4   2.340000+2.100000j
dtype: complex128

0   0.424264
1   1.334166
2   6.754561
3  10.342547
4   3.144137
dtype: float64

在上面的輸出塊中,我們可以看到一個包含複數 Series 結果絕對值的 Series 物件。

更新於:2021年11月18日

630 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.