1
votes

Comment prendre n nombre de tableaux et les définir comme colonnes individuelles dans un tableau plus grand

Je commence par un nombre n de tableaux. Je vais en définir quelques-uns comme exemple.

1 5 3
2 6 6
3 7 7
4 8 8

Comment créer un autre tableau qui aura chacun de mes tableaux de début (X, Y et Z) comme colonnes? Le tableau final ressemblera à ceci:

X = ([1,2,3,4})
Y = ([5,6,7,8])
Z = ([3,6,7,8])


1 commentaires

essayez `column_stack!


3 Réponses :


2
votes

Vous pouvez peut-être essayer comme ceci:

import numpy as np

X = np.array([1,2,3,4])
Y = np.array([5,6,7,8])
Z = np.array([3,6,7,8])
a = np.concatenate((X[:,np.newaxis],Y[:,np.newaxis],Z[:,np.newaxis]),axis=1)


0 commentaires

1
votes

Je ne suis pas un grand fan des bibliothèques tierces, c'est donc une réponse qui n'utilise pas numpy:

>>> X = np.array([1,2,3,4])
>>> Y = np.array([5,6,7,8])
>>> Z = np.array([3,6,7,8])
# timeit.timeit 4.819555767999999

>>> output = np.concatenate((X[:, np.newaxis], Y[:, np.newaxis], Z[:, np.newaxis]), axis=1)
# timeit.timeit 4.175194263
>>> print(output)
[[1 5 3]
 [2 6 6]
 [3 7 7]
 [4 8 8]]

>>> columns = "\n".join([" ".join([str(n) for n in i]) for i in output])
# timeit.timeit 22.564187487
>>> print(columns)
1 5 3
2 6 6
3 7 7
4 8 8

Utilisation de numpy :

>>> X = ([1,2,3,4])
>>> Y = ([5,6,7,8])
>>> Z = ([3,6,7,8])
# timeit.timeit 0.30220915000000004

>>> output = [[X[i], Y[i], Z[i]] for i in range(len(X))]
# timeit.timeit 1.677441058
>>> print(output)
[[1, 5, 3], [2, 6, 6], [3, 7, 7], [4, 8, 8]]

>>> columns = "\n".join([" ".join([str(n) for n in i]) for i in output])
# timeit.timeit 5.729952549999999
>>> print(columns)
1 5 3
2 6 6
3 7 7
4 8 8

>>> for i in range(len(X)):
...    print(X[i], Y[i], Z[i])
1 5 3
2 6 6
3 7 7
4 8 8
# timeit.timeit 1.2027191299999984 without print

Sur les commentaires ( # ), j'ai écrit le temps nécessaire pour exécuter chaque section du code en utilisant timeit. timeit pour que vous puissiez tirer vos propres conclusions.


0 commentaires

1
votes

Il existe une fonction intégrée appelée column_stack à cet effet.

arr = np.vstack((X,Y,Z)).T

Alternativement , vous pouvez utiliser vstack puis transposer

np.column_stack((X, Y, Z))
# array([[1, 5, 3],
#        [2, 6, 6],
#        [3, 7, 7],
#        [4, 8, 8]])


0 commentaires