Skip to main content
 首页 » 编程设计

python之Pandas read_csv 并删除夏令时

2025年05月04日8soundcode

我有一个 312.5MB 的 csv 文件,其中包含从 2003 年 7 月 27 日至今的 EURUSD 1 分钟 OHLC 数据,但所有日期都针对夏令时进行了调整,这意味着我得到了重复和空白。

由于文件太大,默认的日期解析器太慢了,所以我这样做了:

tizo = dateutil.tz.tzfile('/usr/share/zoneinfo/GB') 
def date_parse_1min(s): 
    return datetime(int(s[6:10]),  
                    int(s[3:5]),  
                    int(s[0:2]),  
                    int(s[11:13]), 
                    int(s[14:16]),tzinfo=tizo) 
 
df = read_csv("EURUSD_1m_clean_w_header.csv",index_col=0,parse_dates=True, date_parser=date_parse_1min) 
 
#verify that it's got the tz right: 
df.index 
Exception AttributeError: "'NoneType' object has no attribute 'toordinal'" in 'pandas.tslib._localize_tso' ignored 
Exception AttributeError: "'NoneType' object has no attribute 'toordinal'" in 'pandas.tslib._localize_tso' ignored 
<class 'pandas.tseries.index.DatetimeIndex'> 
[2003-07-26 23:00:00, ..., 2012-12-15 23:59:00] 
Length: 4938660, Freq: None, Timezone: tzfile('/usr/share/zoneinfo/GB') 

不知道为什么那里有属性错误。

df.index.get_duplicates() 
<class 'pandas.tseries.index.DatetimeIndex'> 
[2003-10-26 01:00:00, ..., 2012-10-28 01:59:00] 
Length: 600, Freq: None, Timezone: None 
df1 = df.tz_convert('GMT') 
df1.index.get_duplicates() 
<class 'pandas.tseries.index.DatetimeIndex'> 
[2003-10-26 01:00:00, ..., 2012-10-28 01:59:00] 
Length: 600, Freq: None, Timezone: None 

如何让 pandas 移除夏令时偏移量?显然,我可以计算出需要更改的正确整数索引并像那样做,但必须有更好的方法。

请您参考如下方法:

如果您采用每年的第一个和最后一个重复值并将中间的数据移动一个小时,这应该是更正问题的最简单方法。您显然必须考虑到第一个数据点是从夏令时开始的。