将PeriodIndex转换为

时间:2017-10-04 15:01:13

标签: python pandas bokeh

我有一个使用pd.Period进行索引的数据框,但后来需要使用该数据绘制Bokeh中的x_axis。

df = return_data_with_multiindex()
df.reset_index(inplace=True, drop=False)
type(df["calDate"][0]) # returns pandas._period.Period

不幸的是,Bokeh不支持句号,所以我一直坚持如何最好地转换它。

TypeError: Object of type 'Period' is not JSON serializable

This answer didn't help,因为我仍然在抛出类型错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-287-8753a9594163> in <module>()
      1 #pd.to_datetime(df["calDate"], format='%Y-%m')
----> 2 df["calDate"].to_timestamp()
      3 df[["calDate","freq_hist_deseas","freq_futr","freq_tr12"]]
      4 #type(df["calDate"][0])

C:\ANACONDA36\lib\site-packages\pandas\core\series.py in to_timestamp(self, freq, how, copy)
   2709             new_values = new_values.copy()
   2710 
-> 2711         new_index = self.index.to_timestamp(freq=freq, how=how)
   2712         return self._constructor(new_values,
   2713                                  index=new_index).__finalize__(self)

AttributeError: 'RangeIndex' object has no attribute 'to_timestamp'

有什么想法吗?

编辑:这是一个例子:

                  col1 col2 col3
i1 i2   pd.Period                                                                                   
x   y   2006-07    1   2   3
                   1   2   3

EDIT2:caldate

df.reset_index(inplace=True, drop=False)
df["calDate"].head()

0   2006-07
1   2006-08
2   2006-09
3   2006-10
4   2006-11
Name: calDate, dtype: object

1 个答案:

答案 0 :(得分:3)

我认为您需要将每个句点转换为时间戳,因此请使用lambda,即

示例:

4

输出:

0   2006-07-01
1   2006-08-01
2   2006-09-01
3   2006-10-01
4   2006-11-01
Name: x, dtype: datetime64[ns]
相关问题