當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Pandas DataFrame rpow方法用法及代碼示例

Pandas DataFrame.rpow(~) 方法計算標量、序列、Series 或 DataFrame 以及源 DataFrame 中的值的指數冪,即:

other ** DataFrame

請注意,這與 pow(~) 方法相反,該方法執行以下操作:

DataFrame ** other
注意

除非您使用參數 axislevelfill_value ,否則 rpow(~) 相當於使用 ** 運算符計算指數冪。

參數

1.other | scalarsequenceSeriesDataFrame

生成的 DataFrame 將是 other 和源 DataFrame 的指數冪。

2. axis | intstring | optional

是否為源DataFrame的每一列或每一行廣播other

說明

"index"0

other 針對源 DataFrame 的每一列進行廣播。

"columns"1

other 針對源 DataFrame 的每一行進行廣播。

僅當源 DataFrame 的形狀與 other 的形狀不匹配時,這才相關。默認情況下,axis=1

3. level | intstring | optional

要考慮的級別的名稱或整數索引。僅當您的 DataFrame 是多索引時,這才相關。

4. fill_value | floatNone | optional

在計算指數冪之前替換 NaN 的值。如果計算涉及兩個 NaN ,那麽其結果仍然是 NaN 。默認情況下,fill_value=None

返回值

通過源 DataFrame 和 other 的指數冪計算出的新 DataFrame

例子

基本用法

考慮以下數據幀:

df = pd.DataFrame({"A":[3,4], "B":[5,6]})
df_other = pd.DataFrame({"A":[1,1], "B":[2,2]})



  [df]     |   [df_other]
   A  B    |       A  B
0  3  5    |    0  1  2
1  4  6    |    1  1  2

計算 dfdf_other 的指數冪:

df.rpow(df_other)



   A  B
0  1  32
1  1  64

在這裏,我們計算以下元素級指數冪:

1**3 2**5
1**4 2**6

廣播

考慮以下 DataFrame :

df = pd.DataFrame({"A":[3,4], "B":[5,6]})
df



   A  B
0  3  5
1  4  6
逐行

默認情況下, axis=1 ,這意味著 other 將為 df 中的每一行廣播:

df.rpow([1,2])   # axis=1



   A  B
0  1  32
1  1  64

在這裏,我們計算以下元素級指數冪:

1**3 2**5
1**4 2**6
按列

要為 df 中的每一列廣播 other,請像這樣設置 axis=0

df.rpow([1,2], axis=0)



   A   B
a  1   1
b  16  64

在這裏,我們計算以下元素級指數冪:

1**3 1**5
2**4 2**6

指定fill_value

考慮以下數據幀:

df = pd.DataFrame({"A":[2,np.NaN], "B":[np.NaN,3]})
df_other = pd.DataFrame({"A":[4,5], "B":[np.NaN,np.NaN]})



   A    B     |     A  B
0  2.0  NaN   |  0  4  NaN
1  NaN  3.0   |  1  5  NaN

默認情況下,當我們使用 rpow(~) 計算冪時,任何使用 NaN 的操作都會產生 NaN

df.rpow(df_other)



   A     B
0  16.0  NaN
1  NaN   NaN

在使用 fill_value 參數計算功效之前,我們可以填充 NaN 值:

df.rpow(df_other, fill_value=1)



   A     B
0  16.0  NaN
1  5.0   1.0

這裏,請注意,當運算在兩個 NaN 之間時,無論 fill_value 是什麽,結果仍然是 NaN

相關用法


注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Pandas DataFrame | rpow method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。