Python中基于Pandas DataFrame收盘价两两比较新增NewColumn列
解决方案:给股票DataFrame新增分组对比close列的NewColumn
核心思路
将close列按每2行一组划分,每组内对比第2个值与第1个值的关系,将结果填充到新增的NewColumn中。以下提供两种常见场景的实现方式:
场景1:每组两行都标记对比结果
适合需要让每组内的两行都显示同一对比结论的需求(比如第1、2行都显示第2个收盘价相对第1个的涨跌情况)。
import pandas as pd # 示例股票数据 data = { 'open': [100, 102, 105, 103, 104], 'high': [101, 103, 106, 104, 105], 'low': [99, 101, 104, 102, 103], 'close': [100.5, 102.2, 105.1, 103.5, 104.8] } df = pd.DataFrame(data) # 生成分组标签:每2行一组(索引0-1为组0,2-3为组1,以此类推) df['group'] = df.index // 2 # 定义分组对比函数 def compare_close(group): if len(group) == 2: curr = group.iloc[1] prev = group.iloc[0] if curr > prev: return ['上涨', '上涨'] elif curr < prev: return ['下跌', '下跌'] else: return ['持平', '持平'] # 处理最后一组仅1行的情况 return ['无对比'] # 应用函数到每个分组,生成NewColumn df['NewColumn'] = df.groupby('group')['close'].transform(compare_close) # 移除临时分组列(可选) df = df.drop('group', axis=1) print(df)
执行后输出:
open high low close NewColumn 0 100 101 99 100.50 上涨 1 102 103 101 102.20 上涨 2 105 106 104 105.10 下跌 3 103 104 102 103.50 下跌 4 104 105 103 104.80 无对比
场景2:仅在每组第2行标记对比结果
适合只需要在配对的第二个数据行显示对比结论的需求,第一行留空或标记"待对比"。
import pandas as pd data = { 'open': [100, 102, 105, 103, 104], 'high': [101, 103, 106, 104, 105], 'low': [99, 101, 104, 102, 103], 'close': [100.5, 102.2, 105.1, 103.5, 104.8] } df = pd.DataFrame(data) # 初始化NewColumn为None df['NewColumn'] = None # 遍历每组的第二个元素(索引1、3、5...) for i in range(1, len(df), 2): prev_close = df.loc[i-1, 'close'] curr_close = df.loc[i, 'close'] if curr_close > prev_close: df.loc[i, 'NewColumn'] = '上涨' elif curr_close < prev_close: df.loc[i, 'NewColumn'] = '下跌' else: df.loc[i, 'NewColumn'] = '持平' # 处理最后一行无配对的情况 if len(df) % 2 != 0: df.loc[len(df)-1, 'NewColumn'] = '无对比' print(df)
执行后输出:
open high low close NewColumn 0 100 101 99 100.50 None 1 102 103 101 102.20 上涨 2 105 106 104 105.10 None 3 103 104 102 103.50 下跌 4 104 105 103 104.80 无对比
自定义对比结果
如果不需要文字标签,可修改对比逻辑返回数值或布尔值:
- 返回涨跌差值:将
compare_close函数中的返回值替换为[curr-prev, curr-prev] - 返回布尔值(是否上涨):替换为
[curr>prev, curr>prev]
内容的提问来源于stack exchange,提问作者AMA
相关产品推荐
相关产品推荐

