如何在Pandas中基于当前行与前一行条件创建布尔列
问题:如何为DataFrame添加收盘价涨跌布尔列?
现有如下包含date、open、high、low、close、volume字段的DataFrame:
date open high low close volume 1912 2023-01-05 09:15:00+05:30 641.80 644.30 626.35 628.60 615758 1913 2023-01-05 10:15:00+05:30 628.60 634.50 624.15 628.25 313480 1914 2023-01-05 11:15:00+05:30 627.80 633.45 627.40 632.80 193937 1915 2023-01-05 12:15:00+05:30 632.70 636.05 630.80 634.65 223713 1916 2023-01-05 13:15:00+05:30 634.65 635.00 629.45 634.90 224242 1917 2023-01-05 14:15:00+05:30 634.80 637.90 633.35 635.85 310906 1918 2023-01-05 15:15:00+05:30 635.90 637.35 633.50 633.55 101989
需求是添加一个布尔列,当当前行的close值大于前一行的close值时为True,否则为False。
实现方法
直接利用Pandas的shift()方法获取前一行收盘价,再通过比较生成布尔列,代码如下:
import pandas as pd # 假设你的DataFrame变量名为df df['close_increase'] = df['close'] > df['close'].shift(1)
代码说明
df['close'].shift(1):将close列向下偏移一行,使每一行对应前一行的收盘价,第一行因无前置数据会变为NaN。- 比较操作
df['close'] > df['close'].shift(1)会逐行生成布尔值,最终赋值给新列close_increase。
执行后结果示例
新增列后的DataFrame如下:
date open high low close volume close_increase 1912 2023-01-05 09:15:00+05:30 641.80 644.30 626.35 628.60 615758 NaN 1913 2023-01-05 10:15:00+05:30 628.60 634.50 624.15 628.25 313480 False 1914 2023-01-05 11:15:00+05:30 627.80 633.45 627.40 632.80 193937 True 1915 2023-01-05 12:15:00+05:30 632.70 636.05 630.80 634.65 223713 True 1916 2023-01-05 13:15:00+05:30 634.65 635.00 629.45 634.90 224242 True 1917 2023-01-05 14:15:00+05:30 634.80 637.90 633.35 635.85 310906 True 1918 2023-01-05 15:15:00+05:30 635.90 637.35 633.50 633.55 101989 False
可选优化
如果想将第一行的NaN替换为False(无前置数据默认标记为不上涨),可以添加fillna()处理:
df['close_increase'] = (df['close'] > df['close'].shift(1)).fillna(False)
内容的提问来源于stack exchange,提问作者KawaiKx
相关产品推荐
相关产品推荐

