gpt4 book ai didi

python - tz_localize : KeyError: ('Asia/Singapore' , 你'发生在索引 0')

转载 作者:太空宇宙 更新时间:2023-11-04 02:04:52 31 4
gpt4 key购买 nike

引用:Python pandas convert unix timestamp with timezone into datetime

搜索过这个主题,但仍然找不到答案。

我有一个数据框,格式如下:

df timestamp
1 1549914000
2 1549913400
3 1549935000
3 1549936800
5 1549936200

我使用以下方法将纪元转换为日期:

df['date'] = pd.to_datetime(df['timestamp'], unit='s')

此行将生成一个始终比我的本地时间晚 8 小时的日期。

所以我按照链接中的示例使用 apply + tz.localize to Asia/Singapore,我在上面代码之后的下一行尝试了以下代码。

df['date'] = df.apply(lambda x: x['date'].tz_localize(x['Asia/Singapore']), axis=1)

但是 python 返回如下错误:

Traceback (most recent call last):
File "/home/test/script.py", line 479, in <module>
schedule.every(10).minutes.do(main).run()
File "/opt/cloudera/parcels/Anaconda-4.0.0/lib/python2.7/site-packages/schedule/__init__.py", line 411, in run
ret = self.job_func()
File "/home/test/script.py", line 361, in main
df['date'] = df.apply(localize_ts, axis = 1)
File "/opt/cloudera/parcels/Anaconda-4.0.0/lib/python2.7/site-packages/pandas/core/frame.py", line 4877, in apply
ignore_failures=ignore_failures)
File "/opt/cloudera/parcels/Anaconda-4.0.0/lib/python2.7/site-packages/pandas/core/frame.py", line 4973, in _apply_standard
results[i] = func(v)
File "/home/test/script.py", line 359, in localize_ts
return pd.to_datetime(row['date']).tz_localize(row['Asia/Singapore'])
File "/opt/cloudera/parcels/Anaconda-4.0.0/lib/python2.7/site-packages/pandas/core/series.py", line 623, in __getitem__
result = self.index.get_value(self, key)
File "/opt/cloudera/parcels/Anaconda-4.0.0/lib/python2.7/site-packages/pandas/core/indexes/base.py", line 2574, in get_value
raise e1
KeyError: ('Asia/Singapore', u'occurred at index 0')

我是否正确替换了 .tz_localize(x['tz'])?

最佳答案

如所写,您的代码正在查找名为 Asia/Singapore 的列。试试这个:

df['date'] = df['date'].dt.tz_localize('Asia/Singapore')

关于python - tz_localize : KeyError: ('Asia/Singapore' , 你'发生在索引 0'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54917395/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com