Python元组(Tuple)的使用非常有效,尤其是在大批量数据插入数据库的情况下,非常高效,直接上案例
1.序言
元组(Tuple)一旦定义,就不可被修改(增,删,改),只能查看,无法使用内置函数进行新增元素以及删除元素,但是可以是自定义函数进行增加元素以及删除元素。
而数组可以使用append()函数新增或者是删除元素。
2.创建元组
创建一个元组
tuple0=(1,26)
tuple1=("15","sy")
tuple2=[(1,"a"),(2,"b"),(3,"c")]
创建一个空的元组
Tuple=()
给空的元组赋值
ListA=[1,2,3,4,5]
Tuple=()
for a in range(2):
Tuple=Tuple+(ListA,)
print(Tuple)
读取元组数据
tupe1 = ('physics', 'chemistry', 1997, 2000)
tupe2 = (1, 2, 3, 4, 5, 6, 7 )
print("tupe1[0]: "+ tupe1[0])
print("tupe2[0]: "+ tupe2[0])
3.修改元组
元组内的元素无法进行修改,但是元组之间可以像字符串一样进行运算。
元组之间可以使用 + 号和 * 号进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组
tupe1 = (12, 34.56)
tupe2 = ('abc', 'xyz')
# 以下修改元组元素操作是非法的
# tupe1[0] = 100
# 创建一个新的元组
tupe3 = tupe1 + tupe2
print (tupe3)
#以上实例输出结果:
#(12, 34.56, 'abc', 'xyz')
4.删除元组
tup = ('physics', 'chemistry', 1997, 2000)
print tup
del tup
5.元组的内置函数
Python元组包含了以下内置函数
cmp(tuple1, tuple2):比较两个元组元素。
len(tuple):计算元组元素个数。
max(tuple):返回元组中元素最大值。
min(tuple):返回元组中元素最小值。
tuple(seq):将列表转换为元组。
6.元组在MySQL的方面的应用
元组(Tuple)的使用非常有效,尤其是在大批量数据插入数据库的情况下,非常高效
思路如下:
首先,大数据读取,选择pandas进行读取,具体pandas的用法,可以自行百度。
然后,在pandas读取外部大批量数据,我们选择csv格式类型(xlsx类型的数据读取速度很满,不满足高效率的原则),该文件大约18M,包含47000行,58列数据。
t = time.time()
dir = r'C:\pcCharm Project\20191021\01\风速4ms.csv'
DataFromExcel = pd.read_csv(dir, header=5,low_memory=False)
print("读取原数据.==>> 耗时:{}'s".format(round(time.time() - st, 3)))
#转为DataFrame
DFExcel=pd.DataFrame(DataFromExcel)
其次,将pandas读取到数据(DataFrame)进行处理进行清理,然后转为元组类型(Tuple)。
#丢弃不需要的行
ConvertDFExcel=DFExcel.drop([0,0])
#格式化DataFrame
#删除列名里的空格
ConvertDFExcel = ConvertDFExcel.rename(columns=lambda x: x.replace(" ","")).replace(" ","")
#将TimeMap转为DateTime,以便与MySQL数据类型统一
ConvertDFExcel['Time'] = pd.to_datetime(ConvertDFExcel['Time'])
#将DataFrame转为元组数据
dataTuple = [tuple(xi) for xi in ConvertDFExcel.values]
最后,使用executemany命令插入MySQL数据库。
#设置MySQL连接属性
conn = pymysql.connect(host='localhost', user='root', password='root')
pymysql.charset = 'utf-8'
cur = conn.cursor()
conn.select_db('hkpro')#选择数据库名称
try:
cur.executemany("insert into tp_windv(Time,WindVxi,WindVyi,) values(%s,%s,%s)", dataTuple)
conn.commit()
print("插入数据库成功")
except Exception as err:
print("插入数据库失败")
print("error:",str(err))
finally:
cur.close()
conn.close()
完整代码如下:
import pandas as pd
import pymysql
pymysql.install_as_MySQLdb()
import datetime
import time
##测试版本,可以插入数据库
#字符串进行时间转换
date_string = "2019-09-23 19:56:15"#开始记录时间
date_Convert=datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
#自定义函数分割线************************************开始***************************************自定义函数分割线
#时间递增函数
def AddTime(x):
if is_number(x)==True:
#按秒相加
y = datetime.timedelta(seconds=x) + date_Convert
return y
else:
return x
#字符串前后删除空格函数
def clear(s):
if s[0] == ' ':
return clear(s[1:])
elif s[-1] == ' ':
return clear(s[:-1])
else:
return s
#判断是否是数字
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
#自定义函数分割线************************************结束***************************************自定义函数分割线
st = time.time()
dir = r'C:\pcCharm Project\20191021\01\风速4ms.csv'
DataFromExcel = pd.read_csv(dir, header=5,low_memory=False)
print("读取原数据.==>> 耗时:{}'s".format(round(time.time() - st, 3)))
#转为DataFrame
DFExcel=pd.DataFrame(DataFromExcel)
#丢弃不需要的行
ConvertDFExcel=DFExcel.drop([0,0])
#格式化DataFrame
#删除列名里的空格
ConvertDFExcel = ConvertDFExcel.rename(columns=lambda x: x.replace(" ","")).replace(" ","")
#Object对象转为Float64进行时间运算
ConvertDFExcel['Time'] = pd.to_numeric(ConvertDFExcel['Time'], errors='ignore')
#时间递增加入ConvertDFExcel
ConvertDFExcel['Time']=ConvertDFExcel['Time'].apply(AddTime,0)
#转为元组数组
ConvertDFExcel['Time'] =ConvertDFExcel['Time'].apply(str)
dataTuple = [tuple(xi) for xi in ConvertDFExcel.values]
print("转换原数据.==>> 耗时:{}'s".format(round(time.time() - st, 3)))
conn = pymysql.connect(host='localhost', user='root', password='root')
pymysql.charset = 'utf-8'
cur = conn.cursor()
conn.select_db('hkpro')
try:
cur.executemany("insert into tp_windv1(Time,WindVxi,WindVyi) values(%s,%s,%s)", dataTuple)
conn.commit()
print("插入数据库成功")
except Exception as err:
print("插入数据库失败")
print("error:",str(err))
finally:
cur.close()
conn.close()
print("插入数据库.==>> 耗时:{}'s".format(round(time.time() - st, 3)))
运行结果如下:
事实证明,处理万条数据以及插入数据库的速度不差。
如果使用线程池进行上传数据库,时间会短很多。