Seite 1 von 1

Frage zu Numpy "shape"

Verfasst: Mittwoch 14. Februar 2018, 18:40
von pyzip
Hallo, habe folgendes Verständnisproblem. Ich will aus einem Testdatensatz mehrere Sätze erzeugen. Wenn ich im Code six und siy gleich wähle, dann hat xy das shape (10, 2, six bzw siy) Wenn six und siy verschieden sind, dann zeigt xy das shape (10, 2). Kann mir das bitte jemand erklären??
Vielen Dank und Gruß

Code: Alles auswählen

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 14 18:09:38 2018

@author: Rainer
"""

import numpy as np

six = 9
siy = 9

x = []
for i in range(10):
    m = np.random.randint(1, 30, size=six)
    x.append(m)
x =  np.array(x)
print("x  = ", x)
print("type(x) = ", type(x))
print("x.shape = ", x.shape)
print("x.dtype = ", x.dtype)
print("len(x) = ", len(x))

y = []
for i in range(len(x)):
    m = np.random.randint(1, 30, size=siy)
    y.append(m)
y =  np.array(y)
print("y  = ", y)
print("type(y) = ", type(y))
print("y.shape = ", y.shape)
print("y.dtype = ", y.dtype)
print("len(y) = ", len(y))

xy = []
for d in range(len(x)):
    a = y[d]
    b = x[d]
    xy.append([a, b])
xy = np.array(xy)
print("xy  = ", xy)
print("type(xy) = ", type(xy))
print("xy.shape = ", xy.shape)
print("xy.dtype = ", xy.dtype)
print("len(xy) = ", len(xy))

Re: Frage zu Numpy "shape"

Verfasst: Donnerstag 15. Februar 2018, 08:16
von Sirius3
@pyzip: da die einzelnen Zeilen nicht gleich lang sind, kann man auch keine Matrix daraus erzeugen. Was Numpy macht, ist statt dessen, die Zeile jede Ausgansmatrix als Objekt zu sehen und ein Objekt-Matrix zu erzeugen. Dir ist sicher der unterschiedliche dtype aufgefallen.

Wenn man mit Numpy Schleifen benutzt, macht man meist etwas falsch. Über einen Index zu iterieren ist in Python auch falsch; dafür gibt es zip:

Code: Alles auswählen

import numpy as np
 
six = 9
siy = 9
 
x = np.random.randint(1, 30, size=(10, six))
y = np.random.randint(1, 30, size=(10, siy))
 
xy = []
for a, b in zip(y, x):
    xy.append([a, b])
xy = np.array(xy)
oder kürzer:

Code: Alles auswählen

xy = np.array(zip(y, x))
xy = np.swapaxes(np.array([y, x]), 0, 1)
xy = np.concatenate([y[:,None,:], x[:, None, :]], axis=1)
wobei die letzten beiden Varianten nur funktionieren, wenn six==siy.

Re: Frage zu Numpy "shape"

Verfasst: Donnerstag 15. Februar 2018, 23:07
von pyzip
@Sirius3
danke für die Antwort. Das mit "zip" habe ich auch probiert, aber immer wieder unerklärliche Fehlermeldungen bekommen. Gut ist mein Problem. Und der unterschiedliche dtype ist mir natürlich nicht aufgefallen. Aber jetzt weiß ich, worauf ich achten muß! Danke
Gruß