程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Pandas next row minus previous row

編輯:Python

1.diff() function df['1].diff()
The first result is NAN.

2.shift() function :df['1'].shift(-1) - df['1'] Represents the next line minus the previous line . The last line of the result is NAN.

  • pandas DataFrame.shift() The function can move the data by a specified number of bits .
  • period Parameter specifies the stride of the movement , Can be positive or negative .axis Specifies the axis to move ,1 For the line ,0 Column .
Series.shift(periods=1, freq=None, axis=0, fill_value=None)

shift() function : Default down (axis=0) To the right (axis=1).
If you want to move up and left , You need to set the parameters periods=-1, That is, move up :data.shift(periods=-1, axis=0)
Move to the left :data.shift(periods=-1, axis=1)

3.pandas Single column 、 Multiple columns for calculation
Perform formula calculation for multiple columns :
https://blog.csdn.net/zwhooo/article/details/79696558

4.python Middle up and down 、 Operation between columns

Change the line to the previous line :

df['B'] = math.sqrt(df['A'] * df['A'].shift(periods=-1, axis=0))

Report errors :

terms of settlement :https://stackoverflow.com/questions/42988348/typeerror-cannot-convert-the-series-to-class-float

Change the code to :

df["B"] = (df["A"] * df["A"].shift(periods=-1, axis=0)).apply(lambda x: math.sqrt(x))

5. Calculate the cumulative sum
cumsum() function : Seek before n Cumulative value of elements

df["B"] = df['A'].cumsum(axis=0) # Calculated by line 

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved