简体   繁体   English

Python Pandas Dataframe 减去前一行和前一列

[英]Python Pandas Dataframe subtraction previous row and column

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 1 月 19 日 1255 1255 1123 1123
Feb-19 2 月 19 日 1089 1089 1051 1051
Mar-19 3 月 19 日 943 943 1146 1146
Apr-19 4 月 19 日 897 897 992 992

I would like the output to look something like:我希望输出看起来像:

Date日期 Stock库存 Sold Number售出数量 PrepNumber准备编号
Jan-19 1 月 19 日 1255 1255 1123 1123 957 957
Feb-19 2 月 19 日 1089 1089 1051 1051 905 905
Mar-19 3 月 19 日 943 943 1146 1146 1100 1100
Apr-19 4 月 19 日 897 897 992 992

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

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:您可以使用.shift(-1)获取下一行的条目,并按如下格式设置公式以设置PrepNumber列:

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.有了这个单行代码,Pandas 已经帮助您计算了每一行的结果,而无需将代码放入循环中。 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.这是 Pandas 提供的特性,你应该好好利用它,并尽可能避免循环编码。

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

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.还有一个提示,使用 for 循环来迭代数据帧的记录超过了使用 Pandas 的全部目的,并且应该始终避免使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM