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

Pandas按ts_code分组计算type=1与其他type对应close比值的实现

问题原因

你执行的代码报错是因为groupby返回的是GroupBy对象,不能直接用布尔数组做行筛选,你的写法相当于把布尔值当成列名去查找,才会触发KeyError: 'Column not found: False'。

解决方案

推荐优先使用透视表实现,逻辑更简洁性能更好:

import pandas as pd

# 定义需要计算比值的N值列表
n_list = [5,20,30,60,90,180,200]

# 将长表转为宽表,行索引为ts_code,列是type值,值为对应close
df_pivot = df.pivot(index='ts_code', columns='type', values='close')

# 循环计算每个N对应的比值,保留两位小数,不存在的type自动填充NaN
for n in n_list:
    df_pivot[f'l{n}d_close'] = (df_pivot[1] / df_pivot.get(n, pd.NA)).round(2)

# 提取结果列并重置索引,得到目标格式
result = df_pivot[[f'l{n}d_close' for n in n_list]].reset_index()

如果你偏好使用groupby实现,也可以用自定义聚合函数的方式:

import pandas as pd

n_list = [5,20,30,60,90,180,200]

def calc_group_ratio(group):
    # 取当前ts_code下type=1的基准close值
    base_close = group.loc[group['type'] == 1, 'close'].iloc[0]
    ratio_dict = {}
    for n in n_list:
        n_close = group.loc[group['type'] == n, 'close']
        ratio_dict[f'l{n}d_close'] = round(base_close / n_close.iloc[0], 2) if not n_close.empty else pd.NA
    return pd.Series(ratio_dict)

result = df.groupby('ts_code').apply(calc_group_ratio, include_groups=False).reset_index()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:18:02