Pandas DataFrame.div(~)
方法將源 DataFrame 中的值除以標量、序列、Series 或 DataFrame,即:
DataFrame / other
注意
除非您使用參數 axis
、 level
和 fill_value
,否則 div(~)
相當於使用 /
運算符執行除法。
參數
1.other
| scalar
或 sequence
或 Series
或 DataFrame
生成的 DataFrame 將是源 DataFrame 除以 other
。
2. axis
| int
或 string
| optional
是否為源DataFrame的每一列或每一行廣播other
:
軸 |
說明 |
---|---|
|
每列廣播 |
|
每行廣播 |
僅當源 DataFrame 的形狀與 other
的形狀不對齊時,axis
才相關。默認情況下,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":[20,30], "B":[40,50]})
df_other = pd.DataFrame({"A":[5,6], "B":[4,25]})
A B | A B
0 20 40 | 0 5 4
1 30 50 | 1 6 25
執行除法得到:
df.div(df_other)
A B
0 4.0 10.0
1 5.0 2.0
請注意,這相當於:
df / df_other
A B
0 4.0 10.0
1 5.0 2.0
廣播
考慮以下 DataFrame :
df = pd.DataFrame({"A":[20,30], "B":[40,50]})
df
A B
0 20 40
1 30 50
按行劃分
默認情況下, axis=1
,這意味著 other
將為 df
中的每一行廣播:
df.div([10,100]) # axis=1
A B
0 2.0 0.4
1 3.0 0.5
在這裏,我們進行以下按元素劃分:
20/10 40/100
30/10 50/100
按列劃分
要為 df
中的每一列廣播 other
,請像這樣設置 axis=0
:
df.div([10,100], axis=0)
A B
0 2.0 4.0
1 0.3 0.5
在這裏,我們進行以下按元素劃分:
20/10 40/10
30/100 50/100
指定fill_value
考慮以下 DataFrame :
df = pd.DataFrame({"A": [2,np.NaN], "B":[np.NaN,5]})
df_other = pd.DataFrame({"A":[10,20],"B":[np.NaN,np.NaN]})
A B | A B
0 2.0 NaN | 0 10 NaN
1 NaN 5.0 | 1 20 NaN
默認情況下,當我們使用 div(~)
計算除法時,任何使用 NaN
的操作都會產生 NaN
:
df.div(df_other)
A B
0 0.2 NaN
1 NaN NaN
我們可以在執行除法之前使用 fill_value
參數填充 NaN
值,如下所示:
df.div(df_other, fill_value=100)
A B
0 0.2 NaN
1 5.0 0.05
請注意,當運算在兩個 NaN
之間時,其結果仍然是 NaN
,而不管 fill_value
。
相關用法
- Python Pandas DataFrame diff方法用法及代碼示例
- Python PySpark DataFrame distinct方法用法及代碼示例
- Python PySpark DataFrame dtypes屬性用法及代碼示例
- Python PySpark DataFrame drop方法用法及代碼示例
- Python Pandas DataFrame dtypes屬性用法及代碼示例
- Python PySpark DataFrame dropDuplicates方法用法及代碼示例
- Python Pandas DataFrame duplicated方法用法及代碼示例
- Python Pandas DataFrame drop_duplicates方法用法及代碼示例
- Python Pandas DataFrame dot方法用法及代碼示例
- Python Pandas DataFrame describe方法用法及代碼示例
- Python PySpark DataFrame describe方法用法及代碼示例
- Python Pandas DataFrame drop方法用法及代碼示例
- Python Pandas DataFrame droplevel方法用法及代碼示例
- Python PySpark DataFrame dropna方法用法及代碼示例
- Python Pandas DataFrame dropna方法用法及代碼示例
- Python Pandas DataFrame empty屬性用法及代碼示例
- Python Pandas DataFrame pop方法用法及代碼示例
- Python Pandas DataFrame nsmallest方法用法及代碼示例
- Python Pandas DataFrame sample方法用法及代碼示例
- Python Pandas DataFrame items方法用法及代碼示例
- Python Pandas DataFrame max方法用法及代碼示例
- Python Pandas DataFrame swaplevel方法用法及代碼示例
- Python Pandas DataFrame agg方法用法及代碼示例
- Python Pandas DataFrame copy方法用法及代碼示例
- Python Pandas DataFrame pow方法用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Pandas DataFrame | div method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。