关于python 读取csv最快的Datatable的用法,你都学会了吗
作者:songroom 时间:2022-02-22 20:38:32
2021年7月1日,官方正式发布了1.0Datatable版本。1.0版本支持windows和linux,以及Macos。 具体文档可以见:
https://datatable.readthedocs.io/en/latest/start/using-datatable.html
Datatable与众不同就是快!
需要说明的是,使用Datatable库需要python3.6及以上版本。
import datatable as dt
import pandas as pd
import time
from datetime import date
from datatable import f,update
t0 = time.time()
t1 = time.time()
file = r"C:\Users\songroom\Desktop\000001.csv"
my_table = dt.fread(file,sep=",",header=True) ## datatable格式
## dt.fread(data, sep=",",header=False, columns=["A","B","C","D"]) 多种设置
t3 = time.time()
print(f"my_table -> data type :{type(my_table)}")
print(f"my_table -> data name : {my_table.names}")
print(f"my_table -> (nrows,ncols) : {my_table.shape}") # (nrows, ncols)
my_table -> data type :<class ‘datatable.Frame'>
my_table -> data name : (‘date', ‘open', ‘close', ‘low', ‘high', ‘volume', ‘money', ‘factor', ‘high_limit', ‘low_limit', ‘avg', ‘pre_close', ‘paused', ‘open_interest')
my_table -> (nrows,ncols) : (590880, 14)
print(f"my_table -> head(10) : " )
print(my_table.head(10)) #
print(f" datatable read_csv cost time : {t3-t0} s!")
# ## 和pandas 相比
t4 = time.time()
pandas_df = pd.read_csv(file)
t5 = time.time()
print(f" pandas read_csv cost time : {t5-t4} s! ")
datatable read_csv cost time : 0.059000492095947266 s!
pandas read_csv cost time : 1.7289988994598389 s!
把读取的csv存成jay文件
把.jay文件读成datatable
t6 = time.time()
my_table.to_jay(r"C:\Users\songroom\Desktop\000001.jay")
t7 = time.time()
print(f"datatable 把数据存放成jay cost time : {t7-t6} s!")
## 把.jay文件读成datatable
t8 = time.process_time_ns() ## 增加精度
table_jay = dt.fread(r"C:\Users\songroom\Desktop\000001.jay")
t9 = time.process_time_ns()
print(f"把.jay文件 读取到datatable cost time : {(t9-t8)/1000000000.0} s !")
print(f".jay文件读取成table_jay 的数据格式 :{type(table_jay)}")
datatable 把数据存放成jay cost time : 0.494002103805542 s! 把.jay文件
读取到datatable cost time : 0.0 s !
.jay文件读取成table_jay 的数据格式 :<class ‘datatable.Frame'>
## 把datatable转成pandas.dataframe
t10 = time.time()
pandas_df = my_table.to_pandas()
t11 = time.time()
print(f"pandas_df type : {type(pandas_df)} ")
print(f"datatable 转成 pandas df cost time : {t11-t10} s!")
print(f"{pandas_df.head()}")
pandas_df type : <class ‘pandas.core.frame.DataFrame'> datatable 转成
pandas df cost time : 0.1569967269897461 s!
把dataframe转成datatable
t12 = time.process_time()
my_table_from_df = dt.Frame(pandas_df)
t13 = time.process_time()
print(f"dataframe => datatable cost time : {t13-t12} s!")
print(f"my_table_from_df type: {type(my_table_from_df)} pandas_df type : {type(pandas_df)}")
dataframe => datatable cost time : 0.296875 s! my_table_from_df type:
<class ‘datatable.Frame'> pandas_df type : <class
‘pandas.core.frame.DataFrame'>
把datatable 转成 csv保存,把datatalbe扩展10倍,再输出csv
t14 = time.time()
big_table = dt.repeat(my_table, 10) ##
t14_1 = time.time()
big_table.to_csv(r"C:\Users\songroom\Desktop\000001_big.csv")
t15 = time.time()
print(f"big_table shape (nrows,ncols ) : {big_table.shape}")
print(f"datatable 扩展10倍 cost time : {t14_1-t14}s!")
print(f"datatable 落地csv文件 cost time : {t15-t14_1} s!")
big_table shape (nrows,ncols ) : (5908800, 14)
datatable 扩展10倍 cost time : 0.0s!
datatable 落地csv文件 cost time : 9.905611753463745 s!
与各种类型数据的转换:
datatable => arrow()
arr_from_table = my_table.to_arrow()
print(f"{type(arr_from_table)}")
<class ‘pyarrow.lib.Table'>
把dict =>datatable
dict_data = {"dates" : [date(2000, 1, 5), date(2010, 11, 23), date(2020, 2, 29), None],
"integers" : range(1, 5),
"floats" : [10.0, 11.5, 12.3, -13],
"strings" : ['A', 'B', None, 'D']
}
table_from_dict = dt.Frame(dict_data)
print(f" dict_data type :{type(dict_data)} table_from_dict type : {type(table_from_dict)} ")
把datatable => dict
dict_from_datatable = my_table.to_dict()
print(f" dict_from_datatable type :{type(dict_from_datatable)} my_table type : {type(my_table)} ")
把datatable 取值和过滤
my_table_new = my_table[:, "close"]
找到符合这两个条件(且)的table,这两个条件要括起来!
table_3800_and = my_table[(f.close > 3800) & (f.pre_close < 3800),:]
找到符合这两个条件(or)的table,这两个条件要括起来!
table_3800_or = my_table[(f.close > 3800) | (f.pre_close < 3800),:]
my_table[:, 'date'] ## 选择date列
my_table['date'] ## 同上
my_table[:,["date","close"]] ## 选择 date,close两列
my_table[:,f.close] ## 选择close
my_table[[1, 2, 3], :] ## 选择相应的行
my_table[range(1, 3), :] ## 选择相应的行
把 datatable 转成list
my_list = my_table_new.to_list()
两个datatable的操作 合并
dt1 = dt.rbind(my_table, table_3800_or) ## 这两个table合并,行上进行合并;列上扩展用rbind()
del dt1[:, ['date', 'close']] ## 删除两列
my_table['low_high'] = my_table[:, (f.low + f.high)/2.0] ## 增加一列,赋值方法
my_table[:, update(mean = (f.low+ f.high +f.close)/3.0)] ## 增加一列,update方法
my_table.names = {"low_high": "lowhigh", "mean": "mean_3"} ## 对两列的字段进行重命名
dict_from_datatable type :<class ‘dict'> my_table type : <class ‘datatable.Frame'>
循环,效率好象比较慢!后面还待观察是否有优化!
nrows,ncols = my_table.shape
tt0 = time.time()
for i in range(nrows):
values = my_table[i,:]
tt1 = time.time()
print(f"my_table 循环 cost time :{tt1-tt0} s")
my_table 循环 cost time :9.566002130508423 s。效率看起来比较低。
来源:https://blog.csdn.net/wowotuo/article/details/120809360