- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试为 S&P 500 ETF 创建 30 分钟数据的 PostgreSQL 表(spy30new,用于测试新插入的数据)来自具有 15 分钟数据(all15)的几只股票的表格。 all15 在“dt”(时间戳)和“instr”(股票代码)上有一个索引。我希望 spy30new 在“dt”上有一个索引。
import numpy as np
import pandas as pd
from datetime import datetime, date, time, timedelta
from dateutil import parser
from sqlalchemy import create_engine
# Query all15
engine = create_engine('postgresql://user:passwd@localhost:5432/stocks')
new15Df = (pd.read_sql_query("SELECT dt, o, h, l, c, v FROM all15 WHERE (instr = 'SPY') AND (date(dt) BETWEEN '2016-06-27' AND '2016-07-15');", engine)).sort_values('dt')
# Correct for Time Zone.
new15Df['dt'] = (new15Df['dt'].copy()).apply(lambda d: d + timedelta(hours=-4))
# spy0030Df contains the 15-minute data at 00 & 30 minute time points
# spy1545Df contains the 15-minute data at 15 & 45 minute time points
spy0030Df = (new15Df[new15Df['dt'].apply(lambda d: d.minute % 30) == 0]).reset_index(drop=True)
spy1545Df = (new15Df[new15Df['dt'].apply(lambda d: d.minute % 30) == 15]).reset_index(drop=True)
high = pd.concat([spy1545Df['h'], spy0030Df['h']], axis=1).max(axis=1)
low = pd.concat([spy1545Df['l'], spy0030Df['l']], axis=1).min(axis=1)
volume = spy1545Df['v'] + spy0030Df['v']
# spy30Df assembled and pushed to PostgreSQL as table spy30new
spy30Df = pd.concat([spy0030Df['dt'], spy1545Df['o'], high, low, spy0030Df['c'], volume], ignore_index = True, axis=1)
spy30Df.columns = ['d', 'o', 'h', 'l', 'c', 'v']
spy30Df.set_index(['dt'], inplace=True)
spy30Df.to_sql('spy30new', engine, if_exists='append', index_label='dt')
这给出了错误“ValueError: Cannot cast DatetimeIndex to dtype datetime64[us]”
到目前为止我尝试了什么(我已经使用 Pandas 成功地将 CSV 文件推送到 PG。但这里的源是一个 PG 数据库):
不在 'dt'
上放置索引
spy30Df.set_index(['dt'], inplace=True) # Remove this line
spy30Df.to_sql('spy30new', engine, if_exists='append') # Delete the index_label option
使用 to_pydatetime()
将 'dt' 从类型 pandas.tslib.Timestamp 转换为 datetime.datetime(如果 psycopg2 可以与 python dt 一起工作,但是不是 Pandas 时间戳)
u = (spy0030Df['dt']).tolist()
timesAsPyDt = np.asarray(map((lambda d: d.to_pydatetime()), u))
spy30Df = pd.concat([spy1545Df['o'], high, low, spy0030Df['c'], volume], ignore_index = True, axis=1)
newArray = np.c_[timesAsPyDt, spy30Df.values]
colNames = ['dt', 'o', 'h', 'l', 'c', 'v']
newDf = pd.DataFrame(newArray, columns=colNames)
newDf.set_index(['dt'], inplace=True)
newDf.to_sql('spy30new', engine, if_exists='append', index_label='dt')
使用 datetime.utcfromtimestamp()
timesAsDt = (spy0030Df['dt']).apply(lambda d: datetime.utcfromtimestamp(d.tolist()/1e9))
使用 pd.to_datetime()
timesAsDt = pd.to_datetime(spy0030Df['dt'])
最佳答案
在每个元素上使用 pd.to_datetime() 都有效。选项 4 不起作用,将 pd.to_datetime() 应用于整个系列。也许 Postgres 驱动程序理解 python datetime,但不理解 pandas 和 numpy 中的 datetime64。选项 4 产生了正确的输出,但是在将 DF 发送到 Postgres 时我得到了 ValueError(见标题)
timesAsPyDt = (spy0030Df['dt']).apply(lambda d: pd.to_datetime(str(d)))
关于python - 值错误 : Cannot cast DatetimeIndex to dtype datetime64[us],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38516251/
在 pandas datetimeindex 中,dayofweek和 weekday似乎是一样的。他们只是彼此的别名吗?我发现了这些功能 here 最佳答案 根据pandas源码定义的Datetim
到目前为止,我有 EdChum 提供的以下代码: In [1]: df = pd.DataFrame({'a': [None] * 6, 'b': [2, 3, 10, 3, 5, 8]}) df["
我有一个按日期时间索引的数据框。我正在尝试创建某种过滤器,它只提供包含特定时间的帧。 例如,所有包含“09:30”的帧 df.dtypes open float64 high
不规则时间序列 data存储在 pandas.DataFrame 中.一个 DatetimeIndex已经设置好了。我需要索引中连续条目之间的时间差。 我以为就这么简单 data.index.diff
如何将 DatetimeIndex 更改为像这样的简单数据框: month 0 2013-07-31 1 2013-08-31 2 2013-09-30 3 2013-10-3
我在 pandas 数据框中有多个以下格式的日期列表: col1 col2 1 [DatetimeInde
我有一个 DatetimeIndex 对象,它由两个日期组成,如下所示: import pandas as pd timestamps = pd.DatetimeIndex(['2014-1-1',
我有一个数据框,使用以下代码生成: time_index = pd.date_range(start=datetime(2013, 1, 1, 3), e
我想绘制一个 pandas 系列,其索引是不计其数的 DatatimeIndex。我的代码如下: import matplotlib.dates as mdates index = pd.Dateti
Pandas 在系列/数据帧上有一个 resample 方法,但似乎没有办法单独对 DatetimeIndex 进行重采样? 具体来说,我有一个每日 Datetimeindex,其中可能缺少日期,我想
我已将一组 Excel 文件中的文件名中的日期提取到 DateTimeIndex 对象列表中。我现在需要将每个提取的日期写入我从每个 Excel 工作表创建的数据框的新日期列。我的代码的工作原理是将新
我想计算 DateTimeIndex 中时间之间的时间差 import pandas as pd p = pd.DatetimeIndex(['1985-11-14', '1985-11-28', '
我有一个 pandas.DatetimeIndex ,例如: pd.date_range('2012-1-1 02:03:04.000',periods=3,freq='1ms') >>> [2012
我在单独的 pandas.dataframe 中有两个时间序列,第一个 - series1与第二个条目相比,条目较少且开始数据时间不同 - series2 : index1 = pd.date_ran
我在数据框中有一个带有 DatetimeIndex 的时间序列,如下所示: import pandas as pd dates= ["2015-10-01 00:00:00", "2
当我使用pandas.date_range()时,有时我的时间戳有很多我不想保留的毫秒数。 假设我... import pandas as pd dr = pd.date_range('2011-01
我有一个带有 DateTimeIndex 的 Pandas 数据框和一个名为 WEEKEND 的空列。 如果索引中的日期时间是周末,我想将该列的值设置为“YES”,以便生成的数据帧如下所示: TIME
我有一个包含 12 个值的数据框,我想将其转换为 DatetimeIndex 类型 months = df['date'] #e.g. '2016-04-01' idx = pd.date_range
我处理一个DataFrame,其索引是字符串,年月,例如: index = ['2007-01', '2007-03', ...] 但是,索引未满。例如缺少 2007-02。我想要的是使用完整索引重新
我一直被这样的问题困扰。我有一套客流量的观察。数据存储在.xlsx文件中,结构如下:观察日期、时间、车站名称、登机、下车。 我想知道如果我只需要日期时间的“时间”组件,是否可以从此类数据创建带有 Da
我是一名优秀的程序员,十分优秀!