You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何逐对比较DataFrame的high行值并存储至新DataFrame

逐对比较DataFrame相邻行'high'值并存储结果

假设你的原始DataFrame名为df,以下是几种实现需求的方案:

方案1:提取相邻行'high'的较大值

  • 用shift()方法获取上一行的'high'值,和当前行形成配对
  • 用np.maximum()逐元素比较配对值,取较大者
  • 将结果存入新DataFrame

示例代码:

import pandas as pd
import numpy as np

# 模拟原始DataFrame(可替换为你的真实数据)
df = pd.DataFrame({'high': [386.575, 383.5289, 385.1, 382.0]})

# 计算相邻行high的较大值,跳过无配对的第一行
comparison_results = np.maximum(df['high'], df['high'].shift(1))[1:]

# 转换为新DataFrame
new_df = pd.DataFrame({'comparison_result': comparison_results}).reset_index(drop=True)

print(new_df)

输出示例:

comparison_result
0            386.575
1            385.100
2            385.100

方案2:记录详细比较信息

如果需要标注哪行的'high'值更大,可以扩展结果内容:

# 复制原始数据并添加辅助列
temp_df = df.copy()
temp_df['prev_high'] = temp_df['high'].shift(1)
temp_df['max_high'] = np.where(temp_df['high'] > temp_df['prev_high'], temp_df['high'], temp_df['prev_high'])
temp_df['comparison_note'] = np.where(temp_df['high'] > temp_df['prev_high'], '当前行更大', '上一行更大')

# 生成仅包含比较结果的新DataFrame,过滤无配对的第一行
new_df = temp_df[['max_high', 'comparison_note']].dropna().reset_index(drop=True)

print(new_df)

输出示例:

max_high comparison_note
0   386.575        上一行更大
1   385.100        当前行更大
2   385.100        上一行更大

方案3:所有行两两逐对比较

如果需要的是所有行的两两组合(而非相邻行),可以用以下方式:

from itertools import combinations

# 生成所有行索引的配对组合
row_pairs = list(combinations(df.index, 2))

# 逐对比较并收集结果
results = []
for i, j in row_pairs:
    high_i = df.loc[i, 'high']
    high_j = df.loc[j, 'high']
    results.append({
        'row_pair': f'({i}, {j})',
        'high_row{i}': high_i,
        'high_row{j}': high_j,
        'max_high': max(high_i, high_j)
    })

new_df = pd.DataFrame(results)
print(new_df)

内容的提问来源于stack exchange,提问作者mgr1134

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 12:40:54