将 PeriodIndex 转换为
Converting PeriodIndex to
我有一个使用 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:卡尔达特
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
我认为您需要将每个句点转换为时间戳,因此请使用 lambda,即
示例:
df['x'] = pd.period_range('7/1/2006', '11/1/2006', freq='M')
type(df['x'][0])
#pandas._libs.period.Period
df['x'].apply(lambda x : x.to_timestamp())
输出:
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]
我有一个使用 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:卡尔达特
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
我认为您需要将每个句点转换为时间戳,因此请使用 lambda,即
示例:
df['x'] = pd.period_range('7/1/2006', '11/1/2006', freq='M')
type(df['x'][0])
#pandas._libs.period.Period
df['x'].apply(lambda x : x.to_timestamp())
输出:
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]