如何将熊猫时间序列转换为带字符串键的字典
问题描述:
我需要将熊猫时间序列对象转换为以日期时间为关键字的字典。我尝试了字典(my_ts_obj),但键是Timestamp,而不是字符串。如何将熊猫时间序列转换为带字符串键的字典
非常感谢您的帮助!
答
你可以使用s.index.format()
的时间戳转换成字符串:
In [87]: rng = pd.date_range('12/1/2012', periods=4, freq='D')
In [88]: s = pd.Series(pd.np.random.randn(len(rng)), index=rng)
In [89]: s
Out[89]:
2012-12-01 -1.673655
2012-12-02 1.447061
2012-12-03 -0.672347
2012-12-04 0.202692
Freq: D, dtype: float64
In [90]: dict(zip(s.index.format(), s))
Out[90]:
{'2012-12-01': -1.6736553219187384,
'2012-12-02': 1.4470613776383001,
'2012-12-03': -0.67234662513200982,
'2012-12-04': 0.20269246374288372}
感谢您的回答。这很整洁!我有另一个解决方案,我的原始问题是:dict((str(k),v)for k,v in s.iteritems()) – rxie 2014-11-25 20:26:25