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 theshifted_colslist before concatenation.
内容的提问来源于stack exchange,提问作者user3969377

