python - 如何将 Pandas 时间序列转换为带有字符串键的字典

标签 python dictionary time pandas series

我需要将 Pandas 时间序列对象转换为以日期时间为键的字典。我试过 dict(my_ts_obj),但键是时间戳,而不是字符串。

非常感谢您的帮助!

最佳答案

您可以使用 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}

关于python - 如何将 Pandas 时间序列转换为带有字符串键的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27112865/

相关文章:

php - 如何在此代码 mysql php 中获取小时和分钟

algorithm - O(n log n) 与 O(log n) 有何不同?

python - 如何将多页 PDF 转换为 Python 中的图像对象列表?

python - 如何更改 matplotlib barh 图中的宽度

python - 委托(delegate)给 Python 中的 dict 类

algorithm - 根据距离在 map 上对位置进行分组

python - Python中的舍入时间

python - 获取 Pandas 字符串系列的加权值

python - 在kivy中获取自定义小部件的 "height"属性

c++ - 插入到 Trie 中,NULL 指针