pandas - 使用 Apply 访问 Pandas Dataframe 中前一天的行

标签 pandas

我是 pandas 新手,正在尝试使用昨天的收盘价和今天的价格对每一行进行计算。即:

for 2011-07-26:
    new_column = max(df.high['2011-07-25'], df.close['2011-07-26'])

我考虑过使用迭代所有行,但认为使用 df.apply 函数会更有效。但是,我无法弄清楚如何从我的函数中访问前几天的收盘价。

这是我的数据框的片段。

              open    high     low   close
date                                      
2011-07-22  1597.6  1607.7  1597.5  1601.5
2011-07-25  1618.2  1620.3  1609.4  1612.2
2011-07-26  1610.7  1617.5  1608.0  1616.8

实现这一目标的最佳方法是什么?

最佳答案

你可以做 shift第一:

In [8]: df['yesterday_high'] = df['high'].shift()

In [9]: df
Out[9]: 
              open    high     low   close  yesterday_high
date                                                      
2011-07-22  1597.6  1607.7  1597.5  1601.5             NaN
2011-07-25  1618.2  1620.3  1609.4  1612.2          1607.7
2011-07-26  1610.7  1617.5  1608.0  1616.8          1620.3

然后您可以取昨天最高价和收盘价列的最大值:

In [11]: df[['yesterday_high', 'close']].max(axis=1)
Out[11]: 
date
2011-07-22    1601.5
2011-07-25    1612.2
2011-07-26    1620.3

In [12] df['new_col'] = df[['yesterday_high', 'close']].max(axis=1)

或者:

In [13]: df.apply(lambda x: max(x['yesterday_high'], x['close']), axis=1)
Out[13]: 
date
2011-07-22    1601.5
2011-07-25    1612.2
2011-07-26    1620.3

关于pandas - 使用 Apply 访问 Pandas Dataframe 中前一天的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15610805/

相关文章:

python - 在matplotlib中截断y轴

python - 类型错误 : 'type' object has no attribute '__getitem__' in pandas DataFrame

python - 用kde绘制 Pandas 直方图?

python - 如何删除 Pandas 列中特殊字符前面的部分字符串?

python - 用 pandas 填充信号时保留原始数据点

python - "unfair" Pandas 分类.from_codes

python - 优化旋转和填充

python - 如何将 Pandas DataFrame 转换为 Clustermap 的多索引形式?

python - Pandas:根据另一列的值打印一列的值

Python:基于另一列值的 CSV 文件中的平均值