【问题标题】:How to set a daily frequency in a pandas dataframe?如何在熊猫数据框中设置每日频率?
【发布时间】:2020-12-08 20:51:50
【问题描述】:

这就是我的数据集的样子

Datetime  MinDistance AvgDiameter RelativeV InfinityV               
1900-01-04  0.00962 410.0   8.69    8.65
1900-01-11  0.03989 59.5    10.65   10.65
1900-01-29  0.02076 880.0   5.55    5.52
1900-02-04  0.03201 65.0    3.13    3.11
1900-02-05  0.04903 151.0   10.97   10.97

这就是我导入数据的方式

df = pd.read_csv("ddataset.csv", parse_dates=['Date'])
df['Datetime'] = pd.to_datetime(df['Date'])
df = df.set_index('Datetime')
df.drop(['Date'], axis=1, inplace=True)
print(df.shape)
df.head()

我正在尝试为此数据拟合 VAR 模型。我想将日期时间作为我的索引列。我试过了,

df.index = pd.DatetimeIndex(df.index).to_period('M')
PeriodIndex(['1900-01', '1900-01', '1900-01', '1900-02', '1900-02', '1900-02',
             '1900-02', '1900-02', '1900-03', '1900-03',
             ...
             '2020-04', '2020-04', '2020-04', '2020-04', '2020-04', '2020-04',
             '2020-04', '2020-04', '2020-04', '2020-04'],
            dtype='period[M]', name='Datetime', length=9908, freq='M'

它有效,但我想将我的索引频率设置为“每日”。我用'd'和'D'替换了'M',但它不起作用。我该怎么办?有没有其他方法可以改变频率?

【问题讨论】:

  • 基础数据的周期可能低于每日。您需要调用df.resample('D').asfreq() 重新采样。将为缺少的日期引入一些 NaN 值,这些值必须使用 fillna() 之类的方法进行处理

标签: python pandas time-series


【解决方案1】:

这对我有用,问题是你有 periodIndex 而不是 DatetimeIndex 对象。

df.set_index('Datetime',inplace=True)
df.index=df.index.to_period('D')

其实'PeriodIndex'对象没有'to_period'属性

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-05
    • 2020-12-12
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    • 2015-02-02
    • 2018-12-19
    • 1970-01-01
    相关资源
    最近更新 更多