Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract a Series from a DataFrame while keeping the DataFrame struct intact

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
like image 796
jmatos Avatar asked Dec 11 '13 23:12

jmatos


People also ask

How do you subtract one DataFrame from a different data frame?

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.

How do you subtract values from a data frame?

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.

How do you subtract series in pandas?

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.

How is series DataFrame different from a DataFrame data structure?

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.


1 Answers

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]
like image 193
DSM Avatar answered Sep 21 '22 10:09

DSM