In NumPy, come si può rendere efficiente un oggetto 1-D in un oggetto 2D in cui la dimensione singleton viene dedotta dall'oggetto corrente (ad esempio una lista dovrebbe andare a un vettore 1xlength o lengthx1)?Modo efficiente per aggiungere una dimensione singleton a un vettore NumPy in modo che le assegnazioni slice funzionino
# This comes from some other, unchangeable code that reads data files.
my_list = [1,2,3,4]
# What I want to do:
my_numpy_array[some_index,:] = numpy.asarray(my_list)
# The above doesn't work because of a broadcast error, so:
my_numpy_array[some_index,:] = numpy.reshape(numpy.asarray(my_list),(1,len(my_list)))
# How to do the above without the call to reshape?
# Is there a way to directly convert a list, or vector, that doesn't have a
# second dimension, into a 1 by length "array" (but really it's still a vector)?
Questo è ciò che fa 'np.atleast_2d ([1,2,3,4])'. – hpaulj
@hpaulj sì, ma l'approccio di @DaveP è pulito, salva la seccatura di cercare 'np.atleast_2d' nei documenti e generalizza agli array n-dim (dove n> 3 b/c so che c'è un' np .atleast_3d'). – BoltzmannBrain
Ora c'è un 'np.expand_dims' per gestire tutte le dimensioni. – hpaulj