Python 熊猫无法推断时间序列频率,尽管格式正确?
我有以下数据帧:Python 熊猫无法推断时间序列频率,尽管格式正确?,python,python-3.x,pandas,datetime,Python,Python 3.x,Pandas,Datetime,我有以下数据帧: [1] df.index [1] DatetimeIndex(['1981-01-01', '1981-01-02', '1981-01-03', '1981-01-04', '1981-01-05', '1981-01-06', '1981-01-07', '1981-01-08', '1981-01-09', '1981-01-10', ... '199
[1] df.index
[1] DatetimeIndex(['1981-01-01', '1981-01-02', '1981-01-03', '1981-01-04',
'1981-01-05', '1981-01-06', '1981-01-07', '1981-01-08',
'1981-01-09', '1981-01-10',
...
'1990-12-22', '1990-12-23', '1990-12-24', '1990-12-25',
'1990-12-26', '1990-12-27', '1990-12-28', '1990-12-29',
'1990-12-30', '1990-12-31'],
dtype='datetime64[ns]', name='Date', length=3650, freq=None)
当我尝试将频率设置为每日时:
[2] df.index
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/usr/local/lib/python3.5/dist-packages/pandas/core/arrays/datetimelike.py in _validate_frequency(cls, index, freq, **kwargs)
892 if not np.array_equal(index.asi8, on_freq.asi8):
--> 893 raise ValueError
894 except ValueError as e:
ValueError:
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-23-4e9469ef0e46> in <module>
----> 1 df.index.freq = 'D'
/usr/local/lib/python3.5/dist-packages/pandas/core/indexes/datetimelike.py in freq(self, value)
98 def freq(self, value):
99 # validation is handled by _data setter
--> 100 self._data.freq = value
101
102 @property
/usr/local/lib/python3.5/dist-packages/pandas/core/arrays/datetimelike.py in freq(self, value)
829 if value is not None:
830 value = frequencies.to_offset(value)
--> 831 self._validate_frequency(self, value)
832
833 self._freq = value
/usr/local/lib/python3.5/dist-packages/pandas/core/arrays/datetimelike.py in _validate_frequency(cls, index, freq, **kwargs)
905 "Inferred frequency {infer} from passed values "
906 "does not conform to passed frequency {passed}".format(
--> 907 infer=inferred, passed=freq.freqstr
908 )
909 )
ValueError: Inferred frequency None from passed values does not conform to passed frequency D
您的索引中可能没有连续的天数,但您有连续的月份:
ix = pd.DatetimeIndex(['1981-01-01', '1981-01-02', '1981-01-03', '1981-01-04',
'1981-01-05', '1981-01-06', '1981-01-07', '1981-01-08'],
dtype='datetime64[ns]', name='Date', freq=None)
ix.freq = 'D'
按预期工作,因为日期是连续的,因此您可以将频率设置为天;但是,如果我们将最后一个日期更改为非连续日期:'1981-01-09'
您会收到错误,因为日期不是连续的,因此无法设置为freq='D'
:
ix = pd.DatetimeIndex(['1981-01-01', '1981-01-02', '1981-01-03', '1981-01-04',
'1981-01-05', '1981-01-06', '1981-01-07', '1981-01-09'],
dtype='datetime64[ns]', name='Date', freq=None)
ix.freq = 'D'
ix = pd.DatetimeIndex(['1981-01-01', '1981-01-02', '1981-01-03', '1981-01-04',
'1981-01-05', '1981-01-06', '1981-01-07', '1981-01-09'],
dtype='datetime64[ns]', name='Date', freq=None)
ix.freq = 'D'