如何按每3个日期列垂直拆分目标DataFrame?
Split DataFrame into Chunks of 3 Date Columns (Retaining 'time' Column)
Got it, let's break down how to split your DataFrame exactly as you need it. The key is to keep the time column in every split chunk while grouping the date columns into sets of 3. Here's a straightforward approach using pandas:
Step-by-Step Code Implementation
import pandas as pd # Assume your original DataFrame is named `df` (replace with your actual variable name) # 1. Extract all date columns (skip the first 'time' column) date_columns = df.columns[1:] # 2. Split the date columns into groups of 3 chunked_date_groups = [date_columns[i:i+3] for i in range(0, len(date_columns), 3)] # 3. Generate each split DataFrame and store them in a list split_dataframes = [] for group in chunked_date_groups: # Combine the 'time' column with the current group of date columns chunk_df = df[['time'] + list(group)] split_dataframes.append(chunk_df)
How It Works
- Step 1:
df.columns[1:]grabs all column names starting from the second one, which are your date columns (since the first column istime). - Step 2: The list comprehension uses a range with step size 3 to slice the date columns into chunks of 3. If you have a leftover group with fewer than 3 dates (e.g., 7 total date columns), it will still be included as the final chunk.
- Step 3: We loop through each chunk of date columns, combine them with the
timecolumn, extract the corresponding subset of the original DataFrame, and store each result in thesplit_dataframeslist.
Verify the Result
To check the first split DataFrame (which matches your example), you can print it:
print(split_dataframes[0])
This will output exactly the sample DataFrame you provided.
内容的提问来源于stack exchange,提问作者jerry han
相关产品推荐
相关产品推荐

