如何将Pandas时间序列转换成带字符串键的dict

2024-10-01 22:33:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将Pandas时间序列对象转换为以datetime为键的dicts。我试过dict(mytu-ts-obj),但键是时间戳,而不是字符串。在

万分感谢你的帮助!在


Tags: 对象字符串objpandasdatetime时间序列dict
1条回答
网友
1楼 · 发布于 2024-10-01 22:33:56

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

相关问题 更多 >

    热门问题