熊猫,仅计算最后n行

时间:2020-11-06 22:03:06

标签: pandas dataframe

我正在寻找一种解决方案,以计算最后n行的结果,就像最后一行的结果一样。

import pandas as pd
d = {'col1': [20, 23, 40, 41, 46, 47, 48, 49, 50, 50, 52, 55, 56, 69, 70]}
df = pd.DataFrame(data=d)


df["calc"] = ""  #create new column

# my solution to calculate the value for the last 3 rows
x = df.iloc[-1, df.columns.get_loc('col1')] / df.iloc[-2, df.columns.get_loc('col1')] - 1
df.iloc[-1, df.columns.get_loc('calc')] = x

x = df.iloc[-2, df.columns.get_loc('col1')] / df.iloc[-3, df.columns.get_loc('col1')] - 1
df.iloc[-2, df.columns.get_loc('calc')] = x

x = df.iloc[-3, df.columns.get_loc('col1')] / df.iloc[-4, df.columns.get_loc('col1')] - 1
df.iloc[-3, df.columns.get_loc('calc')] = x

我获得了比复制代码并更改班次更优雅的解决方案。谢谢!

1 个答案:

答案 0 :(得分:2)

要计算最后N

N = 3
df['calc1'] = df.col1.iloc[-N:] / df.col1.iloc[-(N+1):].shift() - 1
df

出局:

    col1       calc     calc1
0     20                  NaN
1     23                  NaN
2     40                  NaN
3     41                  NaN
4     46                  NaN
5     47                  NaN
6     48                  NaN
7     49                  NaN
8     50                  NaN
9     50                  NaN
10    52                  NaN
11    55                  NaN
12    56  0.0181818  0.018182
13    69   0.232143  0.232143
14    70  0.0144928  0.014493