【问题标题】:Monthly averages to daily granularity月平均到日粒度
【发布时间】:2023-01-15 21:58:30
【问题描述】:

我有一个数据框,它是月平均值,如下所示;

    A  B  C  D  E
1   3  21 3 22 3
2   4  32 3 24 0
3   5  1  12 3 12
.  
.
11  5  4  9  85  85 3
12  43 4  48 3  84  4

我希望将此数据转换为每日时间范围,以便数据框成为十年时间序列,并且每个值都对应于其月度值。例如;

           A  B  C  D  E
01/01/2010 3  21 3 22 3
02/01/2010 3  21 3 22 3
.
.
31/01/2010 3  21 3 22 3
.
.
.
30/12/2020 43 4 48 84 4
31/12/2020 43 4 48 84 4

非常感谢任何帮助!

谢谢

【问题讨论】:

    标签: python pandas indexing time-series resample


    【解决方案1】:

    下面是一个示例,说明如何使用 Python 中的 pandas 库将每月数据帧转换为每日时间序列:

    import pandas as pd
    
    # Create a date range for the number of years in the monthly dataframe
    date_rng = pd.date_range(start='2010-01-01', end='2020-12-31', freq='D')
    
    # Create an empty dataframe with the date range as the index
    df = pd.DataFrame(date_rng, columns=['date'])
    df['A'] = 0
    df['B'] = 0
    df['C'] = 0
    df['D'] = 0
    df['E'] = 0
    
    # Set the index of the dataframe to the date column
    df.set_index('date', inplace=True)
    
    # Define the columns from the monthly dataframe
    columns = ['A', 'B', 'C', 'D', 'E']
    
    # Iterate through the rows of the monthly dataframe
    for i, row in monthly_df.iterrows():
        start_date = f"{i}/01/2010"
        end_date = f"{i}/{calendar.monthrange(2010, i)[1]}/2010"
        mask = (df.index >= start_date) & (df.index <= end_date)
        for col in columns:
            df.loc[mask, col] = row[col]
    
    print(df)
    

    这将创建一个日期范围涵盖整个 10 年期间的新数据框,然后它将遍历每月数据框的行,并且对于每一行,它将更新每日数据框中相应列的值整个月的月度值。

    请注意,这只是一个示例,您可能需要根据您的具体用例调整代码。

    【讨论】:

      猜你喜欢
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多