كيف يمكنني استخدام مجموعة منطقية 2-D لتحديد من مجموعة 1-D على أساس لكل صف في نمباي؟

StackOverflow https://stackoverflow.com/questions/442218

  •  22-07-2019
  •  | 
  •  

سؤال

واسمحوا لي توضيح هذه المسألة بمثال:

import numpy

matrix = numpy.identity(5, dtype=bool) #Using identity as a convenient way to create an array with the invariant that there will only be one True value per row, the solution should apply to any array with this invariant
base = numpy.arange(5,30,5) #This could be any 1-d array, provided its length is the same as the length of axis=1 of matrix from above

result = numpy.array([ base[line] for line in matrix ])

وresult يحمل الآن النتيجة المرجوة، ولكن أنا متأكد من أن هناك طريقة نمباي محددة للقيام بذلك أن يتجنب التكرار واضح. ما هو؟

هل كانت مفيدة؟

المحلول

إذا فهمت سؤالك بشكل صحيح يمكنك ببساطة استخدام مصفوفة الضرب:

result = numpy.dot(matrix, base)

إذا يجب أن يكون نتيجة نفس الشكل كما في المثال الخاص بك فقط إضافة إعادة تشكيل:

result = numpy.dot(matrix, base).reshape((5,1))

إذا المصفوفة لا متماثل أن نكون حذرين بشأن الترتيب نقطة.

نصائح أخرى

وهنا هو الطريقة البشعة آخر للقيام بذلك:

n.apply_along_axis(base.__getitem__, 0, matrix).reshape((5,1))

وبلدي محاولة:

numpy.sum(matrix * base, axis=1)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top