Python初学者-“ TypeError:'float'和'str'的实例之间不支持'<'”

时间:2019-09-27 20:56:43

标签: python jupyter-notebook runtime-error

下面是我在Jupyter笔记本中输入的代码,

  • 从熊猫导入read_csv
  • 从matplotlib导入pyplot
  • series = read_csv('daily-minimum-temperatures.csv',header = 0,index_col = 0)
  • resample = series.resample('M')

样本数据:

enter image description here

我遇到以下错误:

TypeError:“ float”和“ str”的实例之间不支持“ <”

请提示我所缺少的内容,请检查以下详细错误:


TypeError Traceback (most recent call last)
<ipython-input-9-93b88286f0b9> in <module>
----> 1 resample = series.resample('M')

//anaconda3/lib/python3.7/site-packages/pandas/core/generic.py in resample(self, rule, how, axis, fill_method, closed, label, convention, kind, loffset, limit, base, on, level)
   8153                      axis=axis, kind=kind, loffset=loffset,
   8154                      convention=convention,
-> 8155                      base=base, key=on, level=level)
   8156         return _maybe_process_deprecations(r,
   8157                                            how=how,

//anaconda3/lib/python3.7/site-packages/pandas/core/resample.py in resample(obj, kind, **kwds)
   1248     """
   1249     tg = TimeGrouper(**kwds)
-> 1250     return tg._get_resampler(obj, kind=kind)
   1251 
   1252 

//anaconda3/lib/python3.7/site-packages/pandas/core/resample.py in _get_resampler(self, obj, kind)
   1358 
   1359         """
-> 1360         self._set_grouper(obj)
   1361 
   1362         ax = self.ax

//anaconda3/lib/python3.7/site-packages/pandas/core/groupby/grouper.py in _set_grouper(self, obj, sort)
    183         if (self.sort or sort) and not ax.is_monotonic:
    184             # use stable sort to support first, last, nth
--> 185             indexer = self.indexer = ax.argsort(kind='mergesort')
    186             ax = ax.take(indexer)
    187             obj = obj._take(indexer, axis=self.axis, is_copy=False)

//anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in argsort(self, *args, **kwargs)
   4338         if result is None:
   4339             result = np.array(self)
-> 4340         return result.argsort(*args, **kwargs)
   4341 
   4342     def get_value(self, series, key):

TypeError: '<' not supported between instances of 'float' and 'str'

1 个答案:

答案 0 :(得分:2)

对于数据帧上的pd.resample,必须为on-参数指定类似日期时间的列,请参见文档中的示例。在这里

df.resample('M', on='Date')

如果“日期”是索引,则没有必要。另外,您还必须将日期列转换为日期时间:

df['Date'] = pd.to_datetime(df['Date'], format='%Y%m%d')

(如果您还没有这样做的话)。