【问题标题】:Change indexing of time in a dataframe更改数据框中时间的索引
【发布时间】:2021-09-28 19:25:54
【问题描述】:
  1. 第一期:

我正在尝试将样本的频率从单独的事件更改为连续范围:

import pandas as pd
all_days= pd.period_range('2020-01-01', '2020-01-08') 
df1=pd.DataFrame.from_dict({'2020-01-04': 2,  '2020-01-07': 10}, 'index')
df_new = df1.reindex(all_days, fill_value=0)

我明白了:

df_new
Out[571]: 
            0
2020-01-01  0
2020-01-02  0
2020-01-03  0
2020-01-04  0
2020-01-05  0
2020-01-06  0
2020-01-07  0
2020-01-08  0

但我想得到:

df_new
Out[571]: 
            0
2020-01-01  0
2020-01-02  0
2020-01-03  0
2020-01-04  2
2020-01-05  0
2020-01-06  0
2020-01-07  10
2020-01-08  0
  1. 更高级的问题:我想对一个数据框执行相同的操作,一个日期有多个值,例如:

     df2=pd.DataFrame([[10, 20],[6, 8],[2, 2]],['2020-01-04',  '2020-01-07',  '2020-01-07'],['A','B'])
    

为:

df_new = df2.reindex(all_days, fill_value=0)

我收到一个错误: ValueError:无法从重复的轴重新索引

但我想得到:

df_new
Out[571]: 
             A   B
2020-01-01   0   0
2020-01-02   0   0
2020-01-03   0   0
2020-01-04  10  20
2020-01-05   0   0
2020-01-06   0   0
2020-01-07   6   8
2020-01-07   2   2
2020-01-08   0   0

【问题讨论】:

    标签: python time-series resampling


    【解决方案1】:

    显然你需要指定索引是一个日期时间索引。 解决方案:

    all_days= pd.date_range('2020-01-01', '2020-01-08') 
    df1=pd.DataFrame.from_dict({'2020-01-04': 2,  '2020-01-07': 10}, 'index')
    df1.index = pd.DatetimeIndex(df1.index)
    df_new = df1.reindex(all_days,enter code here fill_value=0)
    

    【讨论】:

      猜你喜欢
      • 2018-08-24
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2016-03-15
      • 2012-12-11
      • 1970-01-01
      • 2020-04-01
      • 2015-11-23
      相关资源
      最近更新 更多