想了解在python中连接几个np数组的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于python连接数组的相关问题,此外,我们还将为您介绍关于ConnectionPool实现redis在p
想了解在python中连接几个np数组的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于python 连接数组的相关问题,此外,我们还将为您介绍关于ConnectionPool实现redis在python中的连接、python-2.7 – 如何在python中保存3D数组并在mathematica中导入它、python-如何在python中更详细地规范二维numpy数组?、python中连接数据库的新知识。
本文目录一览:- 在python中连接几个np数组(python 连接数组)
- ConnectionPool实现redis在python中的连接
- python-2.7 – 如何在python中保存3D数组并在mathematica中导入它
- python-如何在python中更详细地规范二维numpy数组?
- python中连接数据库
在python中连接几个np数组(python 连接数组)
我有几个颠簸的数组,我想将它们连接起来。我正在使用np.concatenate((array1,array2),axis=1)
。我现在的问题是我想使数组的数量可参数化,我编写了此函数
x1=np.array([1,1])
x2=np.array([0,1])
x3=np.array([1,1,1])
def conc_func(*args):
xt=[]
for a in args:
xt=np.concatenate(a,axis=1)
print xt
return xt
xt=conc_func(x1,x2,x3)
此函数返回([1,1]),我希望它返回([1,1])。我试着在里面添加for循环np.concatenate
这样
xt =np.concatenate((for a in args: a),axis=1)
但我收到语法错误。我既不能使用追加也不能扩展,因为我不得不处理numpy arrays
而不是lists
。有人可以帮忙吗?
提前致谢
ConnectionPool实现redis在python中的连接
今天在写zabbix storm job监控脚本的时候用到了python的redis模块,之前也有用过,但是没有过多的了解,今天看了下相关的api和源码,看到有ConnectionPool的实现,这里简单说下。 在ConnectionPool之前,如果需要连接redis,我都是用StrictRedis这个类,在源码中可以看到这个类的具体解释: redis.StrictRedis Implementation of the Redis protocol.This abstract class provides a Python interface to all Redis commands and an implementation of the Redis protocol.Connection and Pipeline derive from this, implementing how the commands are sent and received to the Redis server
使用的方法:
1
2
|
r
=
redis.StrictRedis(host
=
xxxx, port
=
xxxx, db
=
xxxx)
r.xxxx()
|
有了ConnectionPool这个类之后,可以使用如下方法
1
2
|
pool
=
redis.ConnectionPool(host
=
xxx, port
=
xxx, db
=
xxxx)
r
=
redis.Redis(connection_pool
=
pool)
|
这里Redis是StrictRedis的子类 简单分析如下: 在StrictRedis类的__init__方法中,可以初始化connection_pool这个参数,其对应的是一个ConnectionPool的对象:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class
StrictRedis(
object
):
........
def
__init__(
self
, host
=
''localhost''
, port
=
6379
,
db
=
0
, password
=
None
, socket_timeout
=
None
,
socket_connect_timeout
=
None
,
socket_keepalive
=
None
, socket_keepalive_options
=
None
,
connection_pool
=
None
, unix_socket_path
=
None
,
encoding
=
''utf-8''
, encoding_errors
=
''strict''
,
charset
=
None
, errors
=
None
,
decode_responses
=
False
, retry_on_timeout
=
False
,
ssl
=
False
, ssl_keyfile
=
None
, ssl_certfile
=
None
,
ssl_cert_reqs
=
None
, ssl_ca_certs
=
None
):
if
not
connection_pool:
..........
connection_pool
=
ConnectionPool(
*
*
kwargs)
self
.connection_pool
=
connection_pool
|
在StrictRedis的实例执行具体的命令时会调用execute_command方法,这里可以看到具体实现是从连接池中获取一个具体的连接,然后执行命令,完成后释放连接:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
# COMMAND EXECUTION AND PROTOCOL PARSING
def
execute_command(
self
,
*
args,
*
*
options):
"Execute a command and return a parsed response"
pool
=
self
.connection_pool
command_name
=
args[
0
]
connection
=
pool.get_connection(command_name,
*
*
options)
#调用ConnectionPool.get_connection方法获取一个连接
try
:
connection.send_command(
*
args)
#命令执行,这里为Connection.send_command
return
self
.parse_response(connection, command_name,
*
*
options)
except
(ConnectionError, TimeoutError) as e:
connection.disconnect()
if
not
connection.retry_on_timeout
and
isinstance
(e, TimeoutError):
raise
connection.send_command(
*
args)
return
self
.parse_response(connection, command_name,
*
*
options)
finally
:
pool.release(connection)
#调用ConnectionPool.release释放连接
|
在来看看ConnectionPool类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
class
ConnectionPool(
object
):
...........
def
__init__(
self
, connection_class
=
Connection, max_connections
=
None
,
*
*
connection_kwargs):
#类初始化时调用构造函数
max_connections
=
max_connections
or
2
*
*
31
if
not
isinstance
(max_connections, (
int
,
long
))
or
max_connections <
0
:
#判断输入的max_connections是否合法
raise
ValueError(
''"max_connections" must be a positive integer''
)
self
.connection_class
=
connection_class
#设置对应的参数
self
.connection_kwargs
=
connection_kwargs
self
.max_connections
=
max_connections
self
.reset()
#初始化ConnectionPool 时的reset操作
def
reset(
self
):
self
.pid
=
os.getpid()
self
._created_connections
=
0
#已经创建的连接的计数器
self
._available_connections
=
[]
#声明一个空的数组,用来存放可用的连接
self
._in_use_connections
=
set
()
#声明一个空的集合,用来存放已经在用的连接
self
._check_lock
=
threading.Lock()
.......
def
get_connection(
self
, command_name,
*
keys,
*
*
options):
#在连接池中获取连接的方法
"Get a connection from the pool"
self
._checkpid()
try
:
connection
=
self
._available_connections.pop()
#获取并删除代表连接的元素,在第一次获取connectiong时,因为_available_connections是一个空的数组,
会直接调用make_connection方法
except
IndexError:
connection
=
self
.make_connection()
self
._in_use_connections.add(connection)
#向代表正在使用的连接的集合中添加元素
return
connection
def
make_connection(
self
):
#在_available_connections数组为空时获取连接调用的方法
"Create a new connection"
if
self
._created_connections >
=
self
.max_connections:
#判断创建的连接是否已经达到最大限制,max_connections可以通过参数初始化
raise
ConnectionError(
"Too many connections"
)
self
._created_connections
+
=
1
#把代表已经创建的连接的数值+1
return
self
.connection_class(
*
*
self
.connection_kwargs)
#返回有效的连接,默认为Connection(**self.connection_kwargs)
def
release(
self
, connection):
#释放连接,链接并没有断开,只是存在链接池中
"Releases the connection back to the pool"
self
._checkpid()
if
connection.pid !
=
self
.pid:
return
self
._in_use_connections.remove(connection)
#从集合中删除元素
self
._available_connections.append(connection)
#并添加到_available_connections 的数组中
def
disconnect(
self
):
#断开所有连接池中的链接
"Disconnects all connections in the pool"
all_conns
=
chain(
self
._available_connections,
self
._in_use_connections)
for
connection
in
all_conns:
connection.disconnect()
|
execute_command最终调用的是Connection.send_command方法,关闭链接为 Connection.disconnect方法,而Connection类的实现:
1
2
3
4
5
6
7
|
class
Connection(
object
):
"Manages TCP communication to and from a Redis server"
def
__del__(
self
):
#对象删除时的操作,调用disconnect释放连接
try
:
self
.disconnect()
except
Exception:
pass
|
核心的链接建立方法是通过socket模块实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
def
_connect(
self
):
err
=
None
for
res
in
socket.getaddrinfo(
self
.host,
self
.port,
0
,
socket.SOCK_STREAM):
family, socktype, proto, canonname, socket_address
=
res
sock
=
None
try
:
sock
=
socket.socket(family, socktype, proto)
# TCP_NODELAY
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY,
1
)
# TCP_KEEPALIVE
if
self
.socket_keepalive:
#构造函数中默认 socket_keepalive=False,因此这里默认为短连接
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE,
1
)
for
k, v
in
iteritems(
self
.socket_keepalive_options):
sock.setsockopt(socket.SOL_TCP, k, v)
# set the socket_connect_timeout before we connect
sock.settimeout(
self
.socket_connect_timeout)
#构造函数中默认socket_connect_timeout=None,即连接为blocking的模式
# connect
sock.connect(socket_address)
# set the socket_timeout now that we''re connected
sock.settimeout(
self
.socket_timeout)
#构造函数中默认socket_timeout=None
return
sock
except
socket.error as _:
err
=
_
if
sock
is
not
None
:
sock.close()
.....
|
关闭链接的方法:
1
2
3
4
5
6
7
8
9
10
11
|
def
disconnect(
self
):
"Disconnects from the Redis server"
self
._parser.on_disconnect()
if
self
._sock
is
None
:
return
try
:
self
._sock.shutdown(socket.SHUT_RDWR)
#先shutdown再close
self
._sock.close()
except
socket.error:
pass
self
._sock
=
None
|
可以小结如下 1)默认情况下每创建一个Redis实例都会构造出一个ConnectionPool实例,每一次访问redis都会从这个连接池得到一个连接,操作完成后会把该连接放回连接池(连接并没有释放),可以构造一个统一的ConnectionPool,在创建Redis实例时,可以将该ConnectionPool传入,那么后续的操作会从给定的ConnectionPool获得连接,不会再重复创建ConnectionPool。 2)默认情况下没有设置keepalive和timeout,建立的连接是blocking模式的短连接。 3)不考虑底层tcp的情况下,连接池中的连接会在ConnectionPool.disconnect中统一销毁。
python-2.7 – 如何在python中保存3D数组并在mathematica中导入它
我用Google搜索,我找到了很多答案,我试试这个:
import numpy as np a=np.zeros((2,3,4)) a[0,0]=10 cPickle.dump( a,open( "matrix.txt","wb" ) )
在mathematica中我使用了Import [“matrix.txt”,“Data”]而我没有得到我所期望的
IN[]:Import["matrix.txt","Data"] Out[]:{{"cnumpy.core.multiarray"},{"_reconstruct"},{"p1"},{"(cnumpy"},\ {"ndarray"},{"p2"},{"(I0"},{"tS'b'"},{"tRp3"},{"(I1"},{"(I2"},\ {"I3"},{"I4"},{"tcnumpy"},{"dtype"},{"p4"},{"(S'f8'"},{"I0"},\ {"I1"},{"tRp5"},{"(I3"},{"S'<'"},{"NNNI-1"},{"I-1"},\ {"tbI00"},\ {"S'\\x00\\x00\\x00\\x00\\x00\\x00$@\\x00\\x00\\x00\\x00\\x00\\x00\\\ x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\ x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\ x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\ x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\ x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\ x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\ x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\ x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\ x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\ x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\ x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\ x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\ x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'"},{"tb."}}
解决方法
import numpy as np a=np.zeros((2,0]=10 b=a.reshape(1,24) np.savetxt("/matrix.CSV",b,delimiter=',')
然后在导入后在Mathematica中将其转换为3D,我们可以使用:
file=Import["matrix.CSV","Data"] matrix=ArrayReshape[file,{2,4}]
python-如何在python中更详细地规范二维numpy数组?
给定3乘3的numpy数组
a = numpy.arange(0,27,3).reshape(3,3)# array([[ 0, 3, 6],# [ 9, 12, 15],# [18, 21, 24]])
为了规范二维数组的行,我想到了
row_sums = a.sum(axis=1) # array([ 9, 36, 63])new_matrix = numpy.zeros((3,3))for i, (row, row_sum) in enumerate(zip(a, row_sums)): new_matrix[i,:] = row / row_sum
必须有更好的方法,不是吗?
可能需要澄清:通过标准化我的意思是,每行条目的总和必须为1。但是我认为这对于大多数人来说都是显而易见的。
答案1
小编典典广播确实对此有好处:
row_sums = a.sum(axis=1)new_matrix = a / row_sums[:, numpy.newaxis]
row_sums[:, numpy.newaxis]
重塑row_sums从存在(3,)
到存在(3, 1)
。当你这样做a /b
,a
并b
会相互播出。
您可以
在此处
了解更多有关 广播的
信息
,甚至可以
在此处
了解更多。
python中连接数据库
pymysql是python3版本中用于连接msql服务器的一个库,python2中使用mysqldb
# -*- coding=utf-8 -*- import pymysql #连接db db=pymysql.connect( host=''xxx'', user=''xx'', passwd=''xxx'', db=''xxx'', charset=''utf8'' ) #得到一个可以执行sql语句的光标对象 cur=db.cursor() #定义要执行的sql sql=''select * from xx ;'' #执行sql res=cur.execute(sql) #关闭光标对象 cur.close() #关闭数据库连接 db.close() #一次取一条 print cur.fetchone() #一次取所有 #print cur.fetchall() #自定义取出多少条 print cur.fetchmany(5) #一共多少条数据 print ("%s row in set"%res)
2、增加数据库中的数据
sql1="insert into user_wait_info (user_id,wait_investment_amount) values (%s,%s);" user_id=''b175f39cb43b4d7487aade9fa5c956c1'' wait_investment_amount="2.0" try: #执行sql语句 cur.execute(sql1,(user_id,wait_investment_amount)) #把修改的数据提交到数据库 db.commit() except Exception as e: #捕捉到错误就回滚 db.rollback() cur.close() db.close()
3、删除数据库中的数据
sql2="delete from user_wait_info where user_id=%s; " user_id=''b175f39cb43b4d7487aade9fa5c956c1'' try: cur.execute(sql2,(user_id)) db.commit() except Exception as e: db.rollback() cur.close() db.close()
4、修改数据库中的数据
#修改数据库中的数据 sql3="update user_wait_info set wait_investment_amount=%s where user_id=%s" print sql3 wait_investment_amount=''3.0'' user_id=''2f184953633e45bc9b905d667a3b2c17'' try: cur.execute(sql3,(wait_investment_amount,user_id)) db.commit() except Exception as e: db.rollback() cur.close() db.close()
5、批量操作数据库中的数据
#批量操作数据库中的数据 sql1="insert into user_wait_info (user_id,wait_investment_amount) values (%s,%s);" user_id1=''b175f39cb43b4d7487aade9fa5c956c1'' wait_investment_amount1="2.0" user_id2=''c7d493e14d884f9db89e4372f21307c0'' wait_investment_amount2="3.0" #把所有要插入的信息保存在元组或列表中 data=((user_id1,wait_investment_amount1),(user_id2,wait_investment_amount2)) try: #执行sql语句,使用executemany做批量处理 cur.executemany(sql1,data) #把修改的数据提交到数据库 db.commit() except Exception as e: #捕捉到错误就回滚 db.rollback() cur.close() db.close()
6、获取插入数据的ID
今天的关于在python中连接几个np数组和python 连接数组的分享已经结束,谢谢您的关注,如果想了解更多关于ConnectionPool实现redis在python中的连接、python-2.7 – 如何在python中保存3D数组并在mathematica中导入它、python-如何在python中更详细地规范二维numpy数组?、python中连接数据库的相关知识,请在本站进行查询。
本文标签: