Pandas DataFrame.truediv(~) 方法將源 DataFrame 中的值除以標量、序列、Series 或 DataFrame,即:
DataFrame / other注意
除非您使用參數 axis 、 level 和 fill_value ,否則 truediv(~) 相當於使用 / 運算符執行除法。另外, truediv(~) 相當於  div(~)  。
參數
1.other | scalar 或 sequence 或 Series 或 DataFrame
生成的 DataFrame 將是源 DataFrame 除以 other 。
2. axis | int 或 string | optional
是否為源DataFrame的每一列或每一行廣播other:
| 軸 | 說明 | 
|---|---|
| 
 | 每列廣播 | 
| 
 | 每行廣播  | 
僅當源DataFrame 的形狀與other 的形狀不對齊時,這才相關。默認情況下,axis=1 。
3. level | int 或 string | optional
要考慮的級別的名稱或整數索引。僅當您的 DataFrame 是多索引時,這才相關。
4. fill_value | float 或 None | optional
在計算之前替換NaN的值。請注意,兩個 NaN 之間的除法仍然會導致 NaN 。默認情況下,fill_value=None 。
返回值
分割產生新的DataFrame。
例子
基本用法
考慮以下數據幀:
df = pd.DataFrame({"A":[2,3], "B":[4,5]})
df_other = pd.DataFrame({"A":[1,10], "B":[100,1000]})
   A  B  |     A   B
0  2  4  |  0  1   100
1  3  5  |  1  10  1000執行真正的除法會產生:
df.truediv(df_other)
   A    B
0  2.0  0.040
1  0.3  0.005請注意,這相當於:
df/ df_other
   A    B
0  2.0  0.040
1  0.3  0.005廣播
考慮以下 DataFrame :
df = pd.DataFrame({"A":[2,3], "B":[4,5]})
df
   A   B
0  20  40
1  30  50按行劃分
默認情況下, axis=1 ,這意味著 other 將為 df 中的每一行廣播:
df.truediv([1,10])   # axis=1
   A    B
0  2.0  0.4
1  3.0  0.5在這裏,我們進行以下逐元素浮點除法:
2/1 4/10
3/1 5/10按列劃分
要為 df 中的每一列廣播 other,請像這樣設置 axis=0:
df.truediv([1,10], axis=0)
   A    B
0  2.0  4.0
1  0.3  0.5在這裏,我們進行以下逐元素浮點除法:
2/1 4/1
3/10 5/10指定fill_value
考慮以下數據幀:
df = pd.DataFrame({"A":[12,20],"B":[np.NaN,np.NaN]})
df_other = pd.DataFrame({"A":[3,np.NaN], "B":[np.NaN,4]})
   A    B    |     A   B
0  3.0  NaN  |  0  12  NaN
1  NaN  4.0  |  1  20  NaN默認情況下,當我們使用 truediv(~) 計算除法時,任何使用 NaN 的操作都會產生 NaN :
df.truediv(df_other)
   A    B
0  4.0  NaN
1  NaN  NaN在執行除法之前,我們可以使用fill_value參數填充NaN值:
df.truediv(df_other, fill_value=2)
   A     B
0  4.0   NaN
1  10.0  0.5在這裏,請注意兩個 NaN 之間的除法仍然會導致 NaN,而不管 fill_value 如何。
相關用法
- Python Pandas DataFrame truncate方法用法及代碼示例
- Python Pandas DataFrame transform方法用法及代碼示例
- Python Pandas DataFrame transpose方法用法及代碼示例
- Python PySpark DataFrame transform方法用法及代碼示例
- Python Pandas DataFrame tz_convert方法用法及代碼示例
- Python Pandas DataFrame tail方法用法及代碼示例
- Python Pandas DataFrame to_csv方法用法及代碼示例
- Python Pandas DataFrame tz_localize方法用法及代碼示例
- Python PySpark DataFrame toDF方法用法及代碼示例
- Python PySpark DataFrame toJSON方法用法及代碼示例
- Python Pandas DataFrame tshift方法用法及代碼示例
- Python Pandas DataFrame to_period方法用法及代碼示例
- Python Pandas DataFrame take方法用法及代碼示例
- Python Pandas DataFrame to_json方法用法及代碼示例
- Python PySpark DataFrame tail方法用法及代碼示例
- Python PySpark DataFrame toPandas方法用法及代碼示例
- Python Pandas DataFrame to_timestamp方法用法及代碼示例
- Python Pandas DataFrame to_numpy方法用法及代碼示例
- Python Pandas DataFrame to_dict方法用法及代碼示例
- Python PySpark DataFrame take方法用法及代碼示例
- Python Pandas DataFrame empty屬性用法及代碼示例
- Python Pandas DataFrame pop方法用法及代碼示例
- Python Pandas DataFrame nsmallest方法用法及代碼示例
- Python Pandas DataFrame sample方法用法及代碼示例
- Python Pandas DataFrame items方法用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Pandas DataFrame | truediv method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
