蟒蛇如何修复年份超出范围错误



我正在尝试在csv文件中转换时区,我为此使用的代码曾经工作正常,但由于某种原因,它给了我错误dateutil.parser._parser.ParserError: year 20200320 is out of range: 20200320.0 21:43:00。这很奇怪,因为此代码之前没有发生此错误。

当我尝试使用以下代码重现错误时:

import pandas as pd
#Creating sample dataframe
lst1 = [['Bananas', 'Bali', '20200108', '15:30:00', 1.58, 1.85, 1.50, 1.50],
['Bananas', 'Bali', '20200108', '22:00:00', 1.68, 1.78, 1.40, 1.60],
['Bananas', 'Bali', '20200109', '15:30:00', 1.88, 1.95, 1.70, 1.86],
['Bananas', 'Bali', '20200109', '22:00:00', 1.78, 1.88, 1.60, 1.65],
['Coconut', 'Bahamas', '20200110', '15:30:00', 2.58, 2.85, 2.50, 2.50],
['Coconut', 'Bahamas', '20200110', '22:00:00', 2.68, 2.78, 2.40, 2.60],
['Coconut', 'Bahamas', '20200111', '15:30:00', 2.88, 2.95, 2.70, 2.86],
['Coconut', 'Bahamas', '20200111', '22:00:00', 2.78, 2.88, 2.60, 2.65]]
df1 = pd.DataFrame(lst1, columns =['Name', 'Origin', 'Date', 'Time', 'Open', 'High', 'Low', 'Close'])
print('Second Dataframe')
print(df1)
df1["Datetime"] = df1["Date"].astype(str) + ' ' + df1["Time"].astype(str)
df1["Datetime"] = pd.to_datetime(df1["Datetime"])
df1["Datetime"] = df1["Datetime"].dt.tz_localize('Europe/Paris').dt.tz_convert('US/Eastern')
df1["Datetime"] = df1["Datetime"].dt.tz_localize(None)
df1["Datetime"] = df1["Datetime"].astype(str)
print(df1)

它不会给我错误,即使它是相同的代码和数据。我对此感到非常困惑,我希望这里有人能够帮助我。

我试图将日期除以1000.0,这是 SO 上的一个答案,但随后它给了我一个错误,我无法使用字符串进行计算,但我也无法将日期转换为 datetime64。我希望这里有人知道如何解决这个问题。

编辑: 这是我正在使用的实际.csv文件的示例。如您所见,它有很多空格,我在脚本中删除了这些空格。

Ticker;Exchange;Date;None;Time;Open; High;  Low;    Close;   Volume;   VWAP;      Trades      
AAPL ; NASDAQ ; 20200128; ; 10:00:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 10 ; 0.67 ; 3
AAPL ; NASDAQ ; 20200128; ; 10:01:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 0 ; 0.67 ; 0
AAPL ; NASDAQ ; 20200128; ; 10:02:00 ; 0.66 ; 0.66 ; 0.66 ; 0.66 ; 4 ; 0.66 ; 1
AAPL ; NASDAQ ; 20200128; ; 10:03:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 3 ; 0.67 ; 1
AAPL ; NASDAQ ; 20200128; ; 10:04:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 4 ; 0.67 ; 1
AAPL ; NASDAQ ; 20200128; ; 10:05:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 0 ; 0.67 ; 0
AAPL ; NASDAQ ; 20200128; ; 10:06:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 0 ; 0.67 ; 0
AAPL ; NASDAQ ; 20200128; ; 10:07:00 ; 0.65 ; 0.65 ; 0.65 ; 0.65 ; 4 ; 0.65 ; 1
AAPL ; NASDAQ ; 20200128; ; 10:08:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 2 ; 0.67 ; 1
AAPL ; NASDAQ ; 20200128; ; 10:09:00 ; 0.7 ; 0.7 ; 0.6422 ; 0.6422 ; 16 ; 0.67157 ; 4
AAPL ; NASDAQ ; 20200128; ; 10:10:00 ; 0.7 ; 0.7 ; 0.7 ; 0.7 ; 1 ; 0.7 ; 1

我为此使用的整个代码:

import pandas as pd
import os
print("Converting Timezone")
TEMP = pd.read_csv("Temp\data.csv", sep=";")
#Removing Whitespaces
TEMP.rename(columns=lambda x: x.strip(), inplace=True)
TEMP['Ticker'] = TEMP["Ticker"].astype(str).str.strip()
TEMP['Exchange'] = TEMP["Exchange"].astype(str).str.strip()
TEMP['Date'] = TEMP["Date"].astype(str).str.strip()
TEMP['Time'] = TEMP["Time"].astype(str).str.strip()
TEMP['Open'] = TEMP["Open"].astype(str).str.strip()
TEMP['Open'] = TEMP["Open"].astype(float)
TEMP['High'] = TEMP["High"].astype(str).str.strip()
TEMP['High'] = TEMP["High"].astype(float)
TEMP['Low'] = TEMP["Low"].astype(str).str.strip()
TEMP['Low'] = TEMP["Low"].astype(float)
TEMP['Close'] = TEMP["Close"].astype(str).str.strip()
TEMP['Close'] = TEMP["Close"].astype(float)
TEMP['Volume'] = TEMP["Volume"].astype(str).str.strip()
TEMP['Volume'] = TEMP["Volume"].astype(float)
TEMP['VWAP'] = TEMP["VWAP"].astype(str).str.strip()
TEMP['VWAP'] = TEMP["VWAP"].astype(float)
TEMP['Trades'] = TEMP["Trades"].astype(str).str.strip()
TEMP['Trades'] = TEMP["Trades"].astype(float)
TEMP.drop(columns = ['None'], inplace=True)
#converting dates, here is where I get the error (after print(TEMP))
TEMP["Datetime"] = TEMP["Date"].astype(str) + ' ' + TEMP["Time"].astype(str)
print(TEMP)
TEMP["Datetime"] = pd.to_datetime(TEMP["Datetime"])
TEMP["Datetime"] = TEMP["Datetime"].dt.tz_localize('Europe/Paris').dt.tz_convert('US/Eastern')
TEMP["Datetime"] = TEMP["Datetime"].dt.tz_localize(None)
TEMP["Datetime"] = TEMP["Datetime"].astype(str)
new = TEMP["Datetime"].str.split(" ", n=1, expand=True)
TEMP["Date"] = new[0]
TEMP["Time"] = new[1]
TEMP.drop(columns =["Datetime"], inplace = True)
TEMP["Date"] = pd.to_datetime(TEMP["Date"])
TEMP['Date'] = TEMP.Date.dt.strftime('%Y%m%d')
TEMP["Date"] = TEMP["Date"].astype(str)
TEMP.drop_duplicates(subset=['Ticker', 'Exchange', 'Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume', 'VWAP', 'Trades'], keep='first')
TEMP.sort_values(by=['Date', 'Time'])
print("Dataframe")
print(TEMP)

编辑:

好的,因此对代码进行以下更改似乎可以解决问题,我认为这很奇怪,但不适合它。

TEMP["Datetime"] = pd.to_datetime(TEMP["Datetime"], errors='coerce')

在此行中添加errors='coerce'修复了我没有收到错误。但是,这应该为有错误的每一行返回 NaT 值,但我没有得到任何错误,所以我的所有数据都被转换并且没有发现错误(至少我认为这意味着(,即使它之前说它有错误。我很高兴问题得到解决,但仍然对解决方案感到震惊。

设置"dtype='object"似乎在这里有所帮助,可能是因为我有一个大型数据集。

嗯,有很多话要说。

首先,pandas自动检测每列的类型。使用您的csv数据,所有内容都已正确导入,但列为Date除外,该列作为int64导入。这样就没有必要# removing white spaces整个段落了。请注意,如果您保留此段落,则代码是 100% 有效的。

还要考虑read_csv函数中的选项dtype='object'。因此,每一列都将设置为object数据。

其次,关于您的问题,当我删除第 1 段并仅运行这批代码时,我确实设法获得了类型datetime64[ns]Datetime列:

TEMP = pd.read_csv(file, sep=";")
TEMP.drop(columns = ['None'], inplace=True)
TEMP["Datetime"] = TEMP["Date"].astype(str) + ' ' + TEMP["Time"].astype(str)
TEMP["Datetime"] = pd.to_datetime(TEMP["Datetime"])
print(TEMP)
print(TEMP.dtypes)

最新更新