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

C#中Microsoft.Data.Analysis等效pandas shift列偏移的实现方法

C#实现Microsoft.Data.Analysis等效pandas Shift功能的方案

由于当前Microsoft.Data.Analysis暂未内置Shift列偏移方法,我们可以通过自定义泛型扩展方法实现与pandas shift完全一致的行为,支持正负偏移、空值自动填充。


1. 实现自定义Shift扩展方法

将以下扩展方法加入项目即可直接调用:

using Microsoft.Data.Analysis;

public static class DataFrameExtensions
{
    /// <summary>
    /// 实现与pandas shift完全等效的列偏移功能
    /// </summary>
    /// <param name="column">待偏移的数值列</param>
    /// <param name="offset">偏移量:正数为向下偏移,负数为向上偏移</param>
    /// <typeparam name="T">列的数据类型,需为值类型</typeparam>
    /// <returns>偏移后的新列,空值自动填充为null</returns>
    public static PrimitiveDataFrameColumn<T?> Shift<T>(this PrimitiveDataFrameColumn<T> column, int offset) 
        where T : struct
    {
        long rowCount = column.Length;
        var shiftedColumn = new PrimitiveDataFrameColumn<T?>($"{column.Name}_shift_{offset}", rowCount);

        if (offset > 0)
        {
            // 向下偏移:前offset个位置填null,后续值取原列前rowCount-offset位的值
            for (long i = offset; i < rowCount; i++)
            {
                shiftedColumn[i] = column[i - offset];
            }
        }
        else if (offset < 0)
        {
            // 向上偏移:后|offset|个位置填null,前面的值取原列|offset|位开始的值
            int absOffset = Math.Abs(offset);
            for (long i = 0; i < rowCount - absOffset; i++)
            {
                shiftedColumn[i] = column[i + absOffset];
            }
        }
        else
        {
            // 偏移量为0时直接复制原列值
            for (long i = 0; i < rowCount; i++)
            {
                shiftedColumn[i] = column[i];
            }
        }

        return shiftedColumn;
    }
}

2. 调用示例(与提问中pandas示例效果完全一致)

// 1. 复制原DataFrame
var df2 = df.Clone();

// 2. 获取Col1偏移2位的结果(对应pandas df['Col1'].shift(2))
var col1 = df.Columns.GetPrimitiveColumn<int>("Col1");
var col1Shift2 = col1.Shift(2);
df2.Columns.Add(new PrimitiveDataFrameColumn<int?>("Col4", col1Shift2));

// 3. 计算Col1与偏移2位结果的比值(对应pandas df['Col1'] / df['Col1'].shift(2))
var col5 = new PrimitiveDataFrameColumn<double?>("Col5", df.Rows.Count);
for (long i = 0; i < df.Rows.Count; i++)
{
    if (col1Shift2[i].HasValue)
    {
        col5[i] = (double)col1[i] / col1Shift2[i].Value;
    }
}
df2.Columns.Add(col5);

// 输出结果验证
df2

执行后结果与pandas示例完全一致:

  • Col4列前2行为空值,后续依次为10、20、15
  • Col5列前2行为空值,后续依次为1.5、1.5、3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:15:01