我们如何更改 Pandas DataFrame 中的时区?
我编写了一些简单的代码来读取 1 分钟 EURUSD 数据(日期时间/开盘价/最高价/最低价/收盘价/成交量)。示例数据采用 EST 时区,我需要将其转换为 UTC。
df.tz_convert(pytz.timezone('UTC'))
失败了。有错误
TypeError: Cannot convert tz-naive timestamps, use tz_localize to localize
DAT_ASCII_EURUSD_M1_SmallSample.csv 文件中的示例数据:
20160103 170000;1.087010;1.087130;1.087010;1.087130;0 20160103 170100;1.087120;1.087120;1.087120;1.087120;0 20160103 170200;1.087080;1.087220;1.087080;1.087220;0 20160104 000100;1.087830;1.087840;1.087640;1.087640;0 20160104 000200;1.087640;1.088220;1.087640;1.088220;0 20160104 000300;1.088220;1.088220;1.088040;1.088050;0 20160105 000000;1.082270;1.082270;1.082160;1.082160;0 20160105 000100;1.082160;1.082160;1.082130;1.082140;0 20160105 000200;1.082150;1.082240;1.082150;1.082240;0
import pandas as pd
import pytz
filename = "DAT_ASCII_EURUSD_M1_SmallSample.csv"
df = pd.read_csv(filename, sep=";", names=['DateTime','Open','High','Low','Close','Vol'],
parse_dates = [0], index_col = 'DateTime')
df.tz_localize(pytz.timezone('US/Eastern'))
df.tz_convert(pytz.timezone('UTC'))
print(df)
最佳答案
您应该使用:
df = df.tz_localize(pytz.timezone('US/Eastern'))
df = df.tz_convert(pytz.timezone('UTC'))
因为 tz_localize
不是就地操作,而是返回一个新的 DataFrame。
关于python - Pandas 更改外汇 DataFrame 的时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40533647/