How can I subtract a Series from a DataFrame, while keeping the DataFrame struct intact?
df = pd.DataFrame(np.zeros((5,3)))
s = pd.Series(np.ones(5))
df - s
0 1 2 3 4
0 -1 -1 -1 NaN NaN
1 -1 -1 -1 NaN NaN
2 -1 -1 -1 NaN NaN
3 -1 -1 -1 NaN NaN
4 -1 -1 -1 NaN NaN
What I would like to have is the equivalent of subtracting a scalar from the DataFrame
df - 1
0 1 2
0 -1 -1 -1
1 -1 -1 -1
2 -1 -1 -1
3 -1 -1 -1
4 -1 -1 -1
subtract() function is used for finding the subtraction of dataframe and other, element-wise. This function is essentially same as doing dataframe – other but with a support to substitute for missing data in one of the inputs.
The sub() method subtracts each value in the DataFrame with a specified value. The specified value must be an object that can be subtracted from the values in the DataFrame.
subtract() function basically perform subtraction of series and other, element-wise (binary operator sub). It is equivalent to series - other , but with support to substitute a fill_value for missing data in one of the inputs.
Series can only contain single list with index, whereas dataframe can be made of more than one series or we can say that a dataframe is a collection of series that can be used to analyse the data.
Maybe:
>>> df = pd.DataFrame(np.zeros((5,3)))
>>> s = pd.Series(np.ones(5))
>>> df.sub(s,axis=0)
0 1 2
0 -1 -1 -1
1 -1 -1 -1
2 -1 -1 -1
3 -1 -1 -1
4 -1 -1 -1
[5 rows x 3 columns]
or, for a more interesting example:
>>> s = pd.Series(np.arange(5))
>>> df.sub(s,axis=0)
0 1 2
0 0 0 0
1 -1 -1 -1
2 -2 -2 -2
3 -3 -3 -3
4 -4 -4 -4
[5 rows x 3 columns]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With