Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
about Numpy indexing.
#1
Question 
a = np.arange(25).reshape(5, 5)
a
Output:
array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]])
np.diag(a, k = -1)
Output:
array([ 5, 11, 17, 23])
np.diag(a, k = -2)
Output:
array([10, 16, 22])
How to do like below:
Use feature of np.diag(), indexing specific elements then multiply 10?

a = np.full((5, 5), 1)
Output:
array([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]])
want:
Output:
array([[1, 1, 1, 1, 1], [10, 1, 1, 1, 1], [1, 10, 1, 1, 1], [1, 1, 10, 1, 1], [1, 1, 1, 10, 1]])
Output:
array([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [10, 1, 1, 1, 1], [1, 10, 1, 1, 1], [1, 1, 10, 1, 1]])
Reply
#2
For the first matrix (use the same strategy for the other one)

Paul
import numpy as np
n = 5
M = np.ones( (n,n) )
i = np.arange(1,n)
M[i,i-1] = 10*M[i,i-1]

print(f'M = {M}')
Output:
M = [[ 1. 1. 1. 1. 1.] [10. 1. 1. 1. 1.] [ 1. 10. 1. 1. 1.] [ 1. 1. 10. 1. 1.] [ 1. 1. 1. 10. 1.]]
BashBedlam and Gribouillis like this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Numpy] How to store different data type in one numpy array? water 7 525 Mar-26-2024, 02:18 PM
Last Post: snippsat
  Numpy returns "TypeError: unsupported operand type(s) for *: 'numpy.ufunc' and 'int'" kalle 2 2,594 Jul-19-2022, 06:31 AM
Last Post: paul18fr
  "erlarge" a numpy-matrix to numpy-array PhysChem 2 2,966 Apr-09-2019, 04:54 PM
Last Post: PhysChem
  future warning when using numpy fancy indexing bluefrog 0 4,259 Nov-20-2018, 09:44 AM
Last Post: bluefrog
  Convert indexing For Loop from MATLAB (uses numpy and pandas) bentaz 3 4,180 Mar-20-2018, 08:29 PM
Last Post: bentaz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020