Pandas DataFrame.rsub(~)
方法從標量、序列、Series 或 DataFrame 中減去源 DataFrame 中的值,即:
other - DataFrame
附帶說明一下,這與 DataFrame.sub(~)
正好相反:
DataFrame - other
注意
除非您使用參數 axis
、 level
和 fill_value
,否則 rsub(~)
相當於使用 -
運算符執行減法。
參數
1.other
| scalar
或 sequence
或 Series
或 DataFrame
生成的 DataFrame 將從 other
中減去源 DataFrame 。
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":[1,10], "B":[100,1000]})
df_other = pd.DataFrame({"A":[3,4],"B":[5,6]})
A B | A B
0 1 100 | 0 3 5
1 10 1000 | 1 4 6
從 df_other
中減去 df
得出:
df.rsub(df_other)
A B
0 2 -95
1 -6 -994
廣播
考慮以下 DataFrame :
df = pd.DataFrame({"A":[1,10], "B":[100,1000]})
df
A B
0 1 100
1 10 1000
逐行減法
默認情況下, axis=1
,這意味著 other
將為 df
中的每一行廣播:
df.rsub([3,4]) # axis=1
A B
0 2 -96
1 -7 -996
在這裏,我們進行以下逐元素減法:
3-1 4-100
3-10 4-1000
逐列減法
要為 df
中的每一列廣播 other
,請像這樣設置 axis=0
:
df.rsub([3,4], axis=0)
A B
0 2 -97
1 -6 -996
在這裏,我們進行以下逐元素減法:
3-1 3-100
4-10 4-1000
指定fill_value
考慮以下帶有一些缺失值的DataFrames:
df = pd.DataFrame({"A":[3,np.NaN], "B":[np.NaN,4]})
df_other = pd.DataFrame({"A":[10,100],"B":[np.NaN,np.NaN]})
A B | A B
0 3.0 NaN | 0 10 NaN
1 NaN 4.0 | 1 100 NaN
默認情況下,當我們使用 rsub(~)
執行減法時,任何使用 NaN
的運算都會得到 NaN
:
df.rsub(df_other)
A B
0 7.0 NaN
1 NaN NaN
我們可以在執行減法之前使用 fill_value
參數填充 NaN
值,如下所示:
df.rsub(df_other, fill_value=100)
A B
0 7.0 NaN
1 0.0 96.0
在這裏,請注意兩個 NaN
之間的減法仍然會產生 NaN
,而不管 fill_value
如何。
相關用法
- Python Pandas DataFrame rank方法用法及代碼示例
- Python Pandas DataFrame rdiv方法用法及代碼示例
- Python Pandas DataFrame radd方法用法及代碼示例
- Python PySpark DataFrame repartition方法用法及代碼示例
- Python PySpark DataFrame replace方法用法及代碼示例
- Python PySpark DataFrame rdd屬性用法及代碼示例
- Python Pandas DataFrame reset_index方法用法及代碼示例
- Python Pandas DataFrame reorder_levels方法用法及代碼示例
- Python Pandas DataFrame round方法用法及代碼示例
- Python Pandas DataFrame resample方法用法及代碼示例
- Python Pandas DataFrame reindex方法用法及代碼示例
- Python PySpark DataFrame randomSplit方法用法及代碼示例
- Python Pandas DataFrame replace方法用法及代碼示例
- Python Pandas DataFrame rolling方法用法及代碼示例
- Python Pandas DataFrame rpow方法用法及代碼示例
- Python Pandas DataFrame rfloordiv方法用法及代碼示例
- Python Pandas DataFrame rtruediv方法用法及代碼示例
- Python Pandas DataFrame rename_axis方法用法及代碼示例
- Python Pandas DataFrame rmod方法用法及代碼示例
- Python Pandas DataFrame rmul方法用法及代碼示例
- Python Pandas DataFrame rename方法用法及代碼示例
- Python Pandas DataFrame empty屬性用法及代碼示例
- Python Pandas DataFrame pop方法用法及代碼示例
- Python Pandas DataFrame nsmallest方法用法及代碼示例
- Python Pandas DataFrame sample方法用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Pandas DataFrame | rsub method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。