Pandas 系列是带有轴标签的一维ndarray。标签不必是唯一的,但必须是可哈希的类型。该对象同时支持基于整数和基于标签的索引,并提供了许多方法来执行涉及索引的操作。
Pandas Series.subtract()函数本质上执行系列和其他逐元素的减法(二进制运算符sub)。相当于series - other,但支持用fill_value代替输入之一中的丢失数据。
用法: Series.subtract(other, level=None, fill_value=None, axis=0)
参数:
other:序列或标量值
fill_value:在计算之前,请使用此值填充现有的缺失(NaN)值以及成功进行系列比对所需的任何新元素。
level:在一个级别上广播,在传递的MultiIndex级别上匹配索引值
返回:系列
范例1:采用Series.subtract()函数从元素系列的给定Series对象中减去标量。
# importing pandas as pd
import pandas as pd
# Creating the Series
sr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None])
# Print the series
print(sr)
输出:
现在我们将使用Series.subtract()函数以标量元素为单位执行级数的减法。
# subtract all the elements of the
# series by 10
sr.subtract(10)
输出:
从输出中可以看到,Series.subtract()函数已成功将给定Series对象的所有元素减去10。请注意,尚未对缺失值执行减法。
范例2:采用Series.subtract()函数从元素系列的给定Series对象中减去标量。还将丢失的值替换为100。
# importing pandas as pd
import pandas as pd
# Creating the Series
sr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None])
# Print the series
print(sr)
输出:
现在我们将使用Series.subtract()函数以标量元素为单位执行级数的减法。我们将序列对象中的缺失值替换为100。
# subtract all the elements of the
# series by 10 and also fill 100 at
# the place of missing values.
sr.subtract(10, fill_value = 100)
输出:
从输出中可以看到,Series.subtract()函数已成功将给定Series对象的所有元素减去10。请注意,我们如何在缺失值的位置替换100。