Home > Back-end >  Python Pandas Dataframe subtraction previous row and column
Python Pandas Dataframe subtraction previous row and column

Time:10-13

I am trying to subtract value from a column in a dataframe I am trying to do it like this

for i in range(len(Numbers)-1):
    sub = Numbers.loc[i, 'Stock'] - Numbers.loc[i, 'Sold Number']
    Numbers.loc[i, 'PrepNumber'] = Numbers.loc[i 1, 'Stock'] - sub

but this is not working, I am getting this error

numpy.core._exceptions.UFuncTypeError: ufunc 'subtract' did not contain a loop with signature matching types (dtype('int64'), dtype('<U4')) -> None

Edit:

The data that I have looks something like this:

Date Stock Sold Number
Jan-19 1255 1123
Feb-19 1089 1051
Mar-19 943 1146
Apr-19 897 992

I would like the output to look something like:

Date Stock Sold Number PrepNumber
Jan-19 1255 1123 957
Feb-19 1089 1051 905
Mar-19 943 1146 1100
Apr-19 897 992

Where PrepNumber (Jan-19) = 1089 - (1255 - 1123)

CodePudding user response:

You can make use of .shift(-1) to get the entry of next row, and format the formula as follows to set up the PrepNumber column:

Numbers['PrepNumber'] = Numbers['Stock'].shift(-1) - (Numbers['Stock'] - Numbers['Sold Number'])

With this one-line code, Pandas has already helped you calculated the results for each row without the need to put the codes in a loop. This is the feature that Pandas provides and you should make good use of it and avoid coding in looping style as far as possible.

Result:

print(Numbers)

     Date  Stock  Sold Number  PrepNumber
0  Jan-19   1255         1123       957.0
1  Feb-19   1089         1051       905.0
2  Mar-19    943         1146      1100.0
3  Apr-19    897          992         NaN

CodePudding user response:

your question is not clear, it'd be great if you could provide sample data and the expected results, or explain what you're trying to do a bit more in your future questions.

but if you're trying to add or substract whole columns from each other, and saving the result in a new column then try using this:

Numbers["PrepNumber"] = Numbers["Stock"] - Numbers["Sold Number"]

Also a tip, using for loops to iterate on the records of a dataframe beats the whole purpose of using pandas, and it should be avoided at all times.

  • Related