python / numpy中是否有任何bulid-in函数将spring.datasource.url = jdbc:mysql://localhost:3306/learning
spring.datasource.username = root
spring.datasource.password = root
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = validate
转换为这样的内容:
array = [1, 3, 1, 2]
答案 0 :(得分:12)
您可以创建一个单位矩阵,然后使用索引创建一个新的重新排序的矩阵:
>>> a = np.eye(4)
[Out]: array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
>>> indices = [1, 3, 1, 2]
>>> a[indices]
[Out]: array([[0., 1., 0., 0.],
[0., 0., 0., 1.],
[0., 1., 0., 0.],
[0., 0., 1., 0.]])
答案 1 :(得分:3)
可能最快的是分配零然后设置它们:
>>> def f_preall(a):
... m, n = a.size, a.max()+1
... out = np.zeros((m, n))
... out[np.arange(m), a] = 1
... return out
...
>>> from timeit import timeit
>>>
>>> a = np.random.randint(0, 10, (10,))
>>> timeit(lambda: f_preall(a), number=10000)
0.04905537283048034
>>> timeit(lambda: np.eye(a.max()+1)[a], number=10000)
0.09359440207481384
>>>
>>> a = np.random.randint(0, 100, (100,))
>>> timeit(lambda: f_preall(a), number=10000)
0.10055362526327372
>>> timeit(lambda: np.eye(a.max()+1)[a], number=10000)
0.16951417503878474