Pandas 0.8 を使用して、基盤となる PostgreSQL データベースにクエリを実行しています。Pandas は DataFrame を適切に返しますが、データベースの基になるタイムスタンプ列は、Pandas の一般的な「オブジェクト」型として返されます。最終的にはデータの季節的な正規化を行いたいので、この一般的な「オブジェクト」列を分析に適したものに変換する方法に興味があります。
データを取得するための現在のコードは次のとおりです。
# get timestamp with time zone Pandas example
import pandas.io.sql as psql
import psycopg2
# define query
QRY = """
select
i i,
i * random() f,
case when random() > 0.5
then
true
else
false
end b,
(current_date - (i*random())::int)::timestamp with time zone tsz
from
generate_series(1,1000) as s(i)
order by
4
;
"""
CONN_STRING = "host='localhost' port=5432 dbname='postgres' user='postgres'"
# connect to db
conn = psycopg2.connect(CONN_STRING)
# get some data set index on relid column
df = psql.frame_query(QRY, con=conn)
print "Row count retrieved: %i" % (len(df),)
Python での結果:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1000 entries, 0 to 999
Data columns:
i 1000 non-null values
f 1000 non-null values
b 1000 non-null values
tsz 1000 non-null values
dtypes: bool(1), float64(1), int64(1), object(1)
興味深いことに、最初の列「i」は PG の整数列です。Pandas がこれを「bool」タイプの列と考える理由がわかりません。私の本当の問題は、ある種のタイムスタンプである必要があると思う「オブジェクト」列です。