Cucco’s Compute Hack

コンピュータ関係の記事を書いていきます。

pandasでcsv読みこみ datetime型の型指定で。

pandasでファイルの読み書きのテスト。datetimeの処理が必要なので、型指定の手順を確認。

読んでるファイル 'Book2.csv'
,time,x,y,z
0,2019-03-23 08:53:16,0.384126267,0.791150474,1
1,2019-03-23 08:53:16,0.121509436,0.161273729,3
2,2019-03-23 08:53:16,0.97859278,0.926904462,5
3,2019-03-23 08:53:16,0.824561636,0.455903221,7
4,2019-03-23 08:53:16,0.543611046,0.7457197440000001,9
5,2019-03-23 08:53:16,0.056624959,0.39308888200000003,0
6,2019-03-23 08:53:16,0.912447124,0.7451860359999999,-1
7,2019-03-23 08:53:16,0.354390345,0.881826662,-3
8,2019-03-23 08:53:16,0.7894431120000001,0.256685437,-5
9,2019-03-23 08:53:16,0.758507423,0.067165236,-7
10,2019-03-23 08:53:16,0.400961991,0.547244365,-9
プログラム
import pandas as pd

book2_dtypes = {'time':'str', 'x':'float', 'y':'str','z':'int'}
datetime_format= '%Y-%m-%d %H:%M:%S'
datetime_parser = lambda date: pd.datetime.strptime(date, datetime_format)

df1 = pd.read_csv('Book2.csv', index_col=0, dtype=book2_dtypes, parse_dates=[1], date_parser = datetime_parser)

print(df1["time"].dtype)
print(df1["x"].dtype)
print(df1["y"].dtype)
print(df1["z"].dtype)

print(df1)

df1.to_csv("Book3.csv",sep=",",encoding="utf_8")
実行結果
datetime64[ns]
float64
object
int32
                  time         x                    y  z
0  2019-03-23 08:53:16  0.384126          0.791150474  1
1  2019-03-23 08:53:16  0.121509          0.161273729  3
2  2019-03-23 08:53:16  0.978593          0.926904462  5
3  2019-03-23 08:53:16  0.824562          0.455903221  7
4  2019-03-23 08:53:16  0.543611   0.7457197440000001  9
5  2019-03-23 08:53:16  0.056625  0.39308888200000003  0
6  2019-03-23 08:53:16  0.912447   0.7451860359999999 -1
7  2019-03-23 08:53:16  0.354390          0.881826662 -3
8  2019-03-23 08:53:16  0.789443          0.256685437 -5
9  2019-03-23 08:53:16  0.758507          0.067165236 -7
10 2019-03-23 08:53:16  0.400962          0.547244365 -9