簡體   English   中英

將 DataFrame 的最后 n 行添加到新列中

[英]Add last n rows of DataFrame into a new column

我想在一個新列中添加 dataframe 和 output 的最后 4 個數字,我已經使用 for 循環來做到這一點,但如果有很多行它會更慢有沒有我們可以使用 df.apply(lamda x :) 為達到這個。

**Sample Input: 
    values
0   10
1   20
2   30
3   40
4   50
5   60

Output:
   values result
0   10     10 
1   20     30   
2   30     60
3   40     100
4   50     140
5   60     180**

使用pandas.DataFrame.rolling

>>> df.rolling(4, min_periods=1).sum()
   values
0    10.0
1    30.0
2    60.0
3   100.0
4   140.0
5   180.0
6   220.0
7   260.0
8   300.0

把它加在一起:

>>> df.assign(results=df.rolling(4, min_periods=1).sum().astype(int))
   values  results
0      10       10
1      20       30
2      30       60
3      40      100
4      50      140
5      60      180
6      70      220
7      80      260
8      90      300

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM