GOOGLE ADS

Dienstag, 3. Mai 2022

Wie kann ich am Anfang und am Ende eines Arrays Null hinzufügen?

Ich habe ein Array wie folgt:

contact_map = array([[1., 1., 1.,..., 1., 1., 1.],
[1., 1., 1.,..., 1., 1., 1.],
[1., 1., 1.,..., 1., 1., 1.],
...,
[0., 0., 0.,..., 0., 0., 0.],
[0., 0., 0.,..., 0., 0., 0.],
[0., 0., 0.,..., 0., 0., 0.]])

wobei jedes Element davon ungefähr so ​​​​ist:

contact_map[19] = array([1., 1., 1., 1., 1., 1., 1., 1., 0., 1., 1., 0., 1., 1., 1., 1., 1.,
1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 1., 0.,
0., 0., 0., 0., 0., 1., 0., 1., 1., 1., 1., 0., 0., 1., 1., 0., 0.,
0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 0., 0., 0., 0., 1., 1., 0.,
1., 1., 0., 0., 0., 1., 1., 0., 1., 0., 0., 0., 1., 1., 1., 1., 1.,
1., 0., 1., 0., 0., 0., 0., 1., 0., 0., 1., 0., 1., 1., 1.])

len(kontakt_karte) = 224

len(contact_map[19]) =100

Ich möchte alle Elemente von contact_map so ändern, dass am ersten und am Ende jedes Elements "0" hinzugefügt wird, zum Beispiel das Ändern von contact_map[19] in:

contact_map[19] = array([0.,1., 1., 1., 1., 1., 1., 1., 1., 0., 1., 1., 0., 1., 1., 1., 1., 1.,
1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 1., 0.,
0., 0., 0., 0., 0., 1., 0., 1., 1., 1., 1., 0., 0., 1., 1., 0., 0.,
0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 0., 0., 0., 0., 1., 1., 0.,
1., 1., 0., 0., 0., 1., 1., 0., 1., 0., 0., 0., 1., 1., 1., 1., 1.,
1., 0., 1., 0., 0., 0., 0., 1., 0., 0., 1., 0., 1., 1., 1., 0,.])

len(contact_map[19]) = 102

und so weiter, für contact_map[0], contact_map[1],....

kann mir jemand helfen?


Lösung des Problems

Sie können numpy.padwie folgt verwenden:

>>> import numpy as np
>>> a = np.array([[1., 1., 1., 1., 1., 1.],
[1., 1., 0., 0., 1., 1.],
[0., 1., 0., 0., 1., 1.]])
>>> a.shape
(3, 6)
>>> out = np.pad(a, [(0,0), (1, 1)], 'constant', constant_values=0)
# pad first dimension ^^^ ^^^
# ^^^ pad second dimension
# (first num for set how many pad at first
# second num for... at last.)
>>> out.shape
(3,8)
>>> out
array([[0., 1., 1., 1., 1., 1., 1., 0.],
[0., 1., 1., 0., 0., 1., 1., 0.],
[0., 0., 1., 0., 0., 1., 1., 0.]])

Deine Eingabe:

contact_map = np.random.randint(0,2, (224, 100))
print(len(contact_map))
# 224
print(len(contact_map[19]))
# 100
contact_map = np.pad(contact_map, [(0,0), (1, 1)], 'constant', constant_values=0)
print(len(contact_map[19]))
# 102
print(len(contact_map[0]))
# 102

Keine Kommentare:

Kommentar veröffentlichen

Warum werden SCHED_FIFO-Threads derselben physischen CPU zugewiesen, obwohl CPUs im Leerlauf verfügbar sind?

Lösung des Problems Wenn ich das richtig verstehe, versuchen Sie, SCHED_FIFO mit aktiviertem Hyperthreading ("HT") zu verwenden, ...