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

DataFrame多列多次移位:按nShiftsPerCol生成目标DFO的实现方法

Got it, let's break down how to solve this problem properly! I’ll show you a straightforward, flexible way to generate your target DataFrame DFO where specified columns get multiple shift operations (starting with a 0-shift, meaning no shift at all) and each shifted column gets the shift count appended to its name.

Step 1: Set Up Sample Data (for context)

First, let's define a sample original DataFrame and a sample nShiftsPerCol dictionary to make the example concrete:

import pandas as pd

# Sample original DataFrame
DF = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': [10, 20, 30, 40, 50],
    'C': [100, 200, 300, 400, 500]
})

# Define which columns to shift and their desired shift counts (0 included first)
nShiftsPerCol = {'A': [0, 1, 2], 'B': [0, 3]}

Step 2: Generate the Shifted Columns & Combine into DFO

The core idea is to iterate over each target column and its shift counts, create a new shifted column with the renamed label, then concatenate all these columns into DFO:

# Use a list comprehension to generate all shifted columns cleanly
shifted_cols = [
    DF[col].shift(shift_count).rename(f"{col}_{shift_count}")
    for col, shifts in nShiftsPerCol.items()
    for shift_count in shifts
]

# Combine all shifted columns into the final DFO
DFO = pd.concat(shifted_cols, axis=1)

Step 3: Check the Output

Running the code above will give you this DFO (NaN values are expected for positions where shifting goes beyond the DataFrame's bounds):

A_0  A_1  A_2  B_0   B_3
0  1.0  NaN  NaN   10   NaN
1  2.0  1.0  NaN   20   NaN
2  3.0  2.0  1.0   30   NaN
3  4.0  3.0  2.0   40  10.0
4  5.0  4.0  3.0   50  20.0

Optional: Customize for Your Needs

  • If you want to fill the NaN values (e.g., with 0 or the last valid value), just add .fillna(0) or .ffill() to the shifted column line:
    DF[col].shift(shift_count).fillna(0).rename(f"{col}_{shift_count}")
    
  • If you need to include non-shifted columns from the original DF in DFO, just add them to the shifted_cols list before concatenation.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:29:37