pandas.sub()
时间: 2023-10-30 16:45:38 浏览: 44
The pandas.sub() method is used to subtract a scalar, series, or dataframe from another scalar, series, or dataframe element-wise. The method returns a new object of the same type as the caller with the subtracted values.
Syntax: pandas.DataFrame.sub(other, axis='columns', level=None, fill_value=None)
Parameters:
- other: Scalar, Series, DataFrame or a sequence of these with which to subtract.
- axis: Axis along which to perform the operation. By default, axis=’columns’.
- level: If the axis is a MultiIndex (hierarchical), subtract over a particular level, specified here.
- fill_value: Fill missing (NaN) values with this value. If specified, overrides the default NaN filler.
Returns: Subtracted values of the object.
Note: If two dataframes with different dimensions are subtracted, pandas will automatically align the data based on the index and columns of the dataframes. If a scalar value is subtracted from a dataframe, then that scalar value is subtracted from each element in the dataframe.
Example:
import pandas as pd
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df2 = pd.DataFrame({'A': [1, 2, 3], 'B': [1, 2, 3]})
# Subtracting two dataframes
df3 = df1.sub(df2)
print(df3)
# Subtracting a scalar value from a dataframe
df4 = df1.sub(2)
print(df4)
Output:
A B
0 0 3
1 0 3
2 0 3
A B
0 -1 2
1 0 3
2 1 4