【问题标题】:Pandas convert yearly to monthly熊猫每年转换为每月
【发布时间】:2019-06-29 03:33:30
【问题描述】:

我正在提取财务数据,其中一些是按年格式化的,而另一些是按月格式化的。我的模型每月都需要所有这些,因此我需要每个月重复相同的年度值。我一直在使用这个stack post 并尝试使代码适应我的数据。

这是我的数据框:

df.head()

   date ticker value
0 1999-12-31  ECB/RA6  1.0
1 2000-12-31  ECB/RA6  4.0
2 2001-12-31  ECB/RA6  2.0
3 2002-12-31  ECB/RA6  3.0
4 2003-12-31  ECB/RA6  2.0

这是我想要的前 5 行输出:

   date ticker value
0 1999-12-31  ECB/RA6  1.0
1 2000-01-31  ECB/RA6  4.0
2 2000-02-28  ECB/RA6  4.0
3 2000-13-31  ECB/RA6  4.0
4 2000-04-30  ECB/RA6  4.0

还有我的代码:

df['date'] = pd.to_datetime(df['date'], format='%Y-%m')
df = df.pivot(index='date', columns='ticker')
start_date = df.index.min() - pd.DateOffset(day=1)
end_date = df.index.max() + pd.DateOffset(day=31)
dates = pd.date_range(start_date, end_date, freq='M')
dates.name = 'date'
df = df.reindex(dates, method='ffill')

df = df.stack('ticker')
df = df.sortlevel(level=1)
df = df.reset_index()

但是,它并没有像预期的那样重复几个月

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你想要resample

    首先,您需要设置索引,以便resample 可以工作。然后你回填并重置索引。

    df.set_index('date').resample('M').bfill().reset_index()
    
             date   ticker  value
    0  1999-12-31  ECB/RA6    1.0
    1  2000-01-31  ECB/RA6    4.0
    2  2000-02-29  ECB/RA6    4.0
    3  2000-03-31  ECB/RA6    4.0
    4  2000-04-30  ECB/RA6    4.0
    5  2000-05-31  ECB/RA6    4.0
    6  2000-06-30  ECB/RA6    4.0
    7  2000-07-31  ECB/RA6    4.0
    8  2000-08-31  ECB/RA6    4.0
    9  2000-09-30  ECB/RA6    4.0
    10 2000-10-31  ECB/RA6    4.0
    11 2000-11-30  ECB/RA6    4.0
    12 2000-12-31  ECB/RA6    4.0
    13 2001-01-31  ECB/RA6    2.0
    14 2001-02-28  ECB/RA6    2.0
    15 2001-03-31  ECB/RA6    2.0
    ...
    

    按照ticker处理此问题

    df.set_index('date').groupby('ticker', group_keys=False) \
        .resample('M').bfill().reset_index()
    

    【讨论】:

    • 我收到错误 ValueError: cannot reindex a non-unique index with a method or limit
    • 我认为原因是我有多个代码,因此日期重复
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 2018-10-23
    • 2021-04-24
    • 2020-12-09
    • 2021-12-06
    • 2016-10-27
    • 2016-07-13
    相关资源
    最近更新 更多