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

基于指定月份拆分近5个月的Dataframe为独立子Dataframe

解决方法:拆分DataFrame为独立月度DF或多列

Hey there! Let's walk through how to solve your problem with pandas. We'll cover both creating individual monthly DataFrames and reshaping your data into 5 columns named after the months.


前提准备:确保日期列格式正确

First, let's make sure your date column is properly parsed as datetime (this is critical for filtering by month/year):

import pandas as pd

# 示例数据(替换成你的真实DataFrame)
data = {
    'date': pd.date_range(start='2019-01-01', end='2019-08-31', freq='D'),
    'amount': [i*2 for i in range(len(pd.date_range(start='2019-01-01', end='2019-08-31')))]
}
df = pd.DataFrame(data)

# 转换date列为datetime类型
df['date'] = pd.to_datetime(df['date'])

方法1:创建5个独立的月度DataFrames

You specified excluding the input month (August 2019) and creating DataFrames for July to March (5 months total). Here's how to do it:

步骤1:定义目标月份范围

First, calculate the 5 target months (from July 2019 back to March 2019):

target_year = 2019
target_month = 8  # 输入的月份

# 生成目标月份的(year, month)元组列表
target_months = []
for offset in range(1, 6):
    current_month = target_month - offset
    current_year = target_year
    # 处理跨年度情况(比如如果输入1月,倒推会到前一年的12月)
    if current_month < 1:
        current_month += 12
        current_year -= 1
    target_months.append( (current_year, current_month) )

# 此时target_months = [(2019,7), (2019,6), (2019,5), (2019,4), (2019,3)]

步骤2:创建独立DataFrames

You can create them manually, or use a loop to automate the naming:

手动创建(直观)

# 七月数据
jul_df = df[(df['date'].dt.year == target_months[0][0]) & (df['date'].dt.month == target_months[0][1])]
# 六月数据
jun_df = df[(df['date'].dt.year == target_months[1][0]) & (df['date'].dt.month == target_months[1][1])]
# 五月数据
may_df = df[(df['date'].dt.year == target_months[2][0]) & (df['date'].dt.month == target_months[2][1])]
# 四月数据
apr_df = df[(df['date'].dt.year == target_months[3][0]) & (df['date'].dt.month == target_months[3][1])]
# 三月数据
march_df = df[(df['date'].dt.year == target_months[4][0]) & (df['date'].dt.month == target_months[4][1])]

自动创建(适合批量操作)

If you have more months to handle, a loop can save time:

# 对应月份的缩写(用于命名DataFrame)
month_names = ['jul', 'jun', 'may', 'apr', 'march']

for idx, (year, month) in enumerate(target_months):
    # 筛选对应月份的数据
    month_data = df[(df['date'].dt.year == year) & (df['date'].dt.month == month)]
    # 将DataFrame赋值为全局变量(比如jul_df, jun_df等)
    globals()[f"{month_names[idx]}_df"] = month_data

方法2:拆分为以月份名为列的5列

If you want to reshape the data so each month becomes a column, here are two common scenarios:

场景1:保留每日数据(日期为索引)

This will give you a DataFrame where each row is a date, and columns are the amount values for each target month:

# 先筛选出目标5个月的数据
filtered_data = df[
    df['date'].apply(lambda x: (x.year, x.month) in target_months)
]

# 添加月份名称列(小写缩写)
filtered_data['month'] = filtered_data['date'].dt.strftime('%b').str.lower()

# 透视数据:日期为索引,月份为列,amount为值
monthly_columns_df = filtered_data.pivot(index='date', columns='month', values='amount')

# 调整列顺序为jul → jun → may → apr → march,填充缺失值为0(可选)
monthly_columns_df = monthly_columns_df[['jul', 'jun', 'may', 'apr', 'march']].fillna(0)

场景2:月度汇总数据(一行展示5个月的总额)

If you just need the total amount per month as columns:

# 按年份和月份分组,计算每月总额
monthly_totals = filtered_data.groupby(
    [filtered_data['date'].dt.year, filtered_data['date'].dt.month]
)['amount'].sum().reset_index()

# 添加月份名称
monthly_totals['month'] = monthly_totals['date'].dt.strftime('%b').str.lower()

# 转置为列格式
summary_columns_df = monthly_totals.set_index('month')['amount'].rename_axis(None).to_frame().T[['jul', 'jun', 'may', 'apr', 'march']]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:20:45