为什么会出现此错误-KeyError :('datetime64 [ns]','left')?

时间:2019-07-19 09:08:51

标签: python-3.x

当我运行下面的代码时,将显示此错误:

KeyError: ('datetime64[ns]', 'left')

任何人都有答案吗?这是代码:

def transform_in_intervals(df,freq=to_offset('5t')):
    df = df.copy()
    time = df.index
    interval = pd.interval_range(start=time[0],periods=(time[-1]-time[0])/pd.Timedelta(freq)+1,freq=freq,closed="left")
    df.reset_index(False,inplace=True)
    i, c = 0, 0
    while i < len(df):
        if df.loc[i,"time"] in interval[c]:
            df.loc[i,"interval"] = interval[c]
            i += 1
        else:
            c += 1
    df_res = pd.DataFrame([])
    for iv, df_left in df.groupby("interval"):
        df_res = df_res.append(df_left.drop("time",axis=1).mean(),ignore_index=True)
    df_res.set_index(interval,inplace=True)
    return df_res
start= time.time()
trans_df = transform_in_intervals(merged_df)
end = time.time()
print("time:{:.3f} s".format(end-start))

KeyError                                  Traceback (most recent call last)
<ipython-input-31-bfcffbdad696> in <module>()
      1 start= time.time()
----> 2 trans_df = transform_in_intervals(merged_df)
      3 end = time.time()
      4 print("time:{:.3f} s".format(end-start))

<ipython-input-30-2d97dbfdb4d1> in transform_in_intervals(df, freq)
     14     for iv, df_left in df.groupby("interval"):
     15         df_res = df_res.append(df_left.drop("time",axis=1).mean(),ignore_index=True)
---> 16     df_res.set_index(interval,inplace=True)
     17     return df_res

~\AppData\Local\Continuum\anaconda2\envs\py35\lib\site-packages\pandas\core\frame.py in set_index(self, keys, drop, append, inplace, verify_integrity)
   3921 
   3922         # clear up memory usage
-> 3923         index._cleanup()
   3924 
   3925         frame.index = index

~\AppData\Local\Continuum\anaconda2\envs\py35\lib\site-packages\pandas\core\indexes\base.py in _cleanup(self)
   1912 
   1913     def _cleanup(self):
-> 1914         self._engine.clear_mapping()
   1915 
   1916     @cache_readonly

pandas\_libs\properties.pyx in pandas._libs.properties.CachedProperty.__get__()

~\AppData\Local\Continuum\anaconda2\envs\py35\lib\site-packages\pandas\core\indexes\interval.py in _engine(self)
    366     @cache_readonly
    367     def _engine(self):
--> 368         return IntervalTree(self.left, self.right, closed=self.closed)
    369 
    370     @property

pandas\_libs\intervaltree.pxi in pandas._libs.interval.IntervalTree.__init__()

KeyError: ('datetime64[ns]', 'left')

0 个答案:

没有答案