3

I'm having trouble changing the values in a numpy array. I have already set up the array of zeros. Pvfv is present value and future value

pvfv=np.zeros((7,5))
print(pvfv)

Output:

[[ 0.00     0.00     0.00     0.00     0.00]
 [ 0.00     0.00     0.00     0.00     0.00]
 [ 0.00     0.00     0.00     0.00     0.00]
 [ 0.00     0.00     0.00     0.00     0.00]
 [ 0.00     0.00     0.00     0.00     0.00]
 [ 0.00     0.00     0.00     0.00     0.00]
 [ 0.00     0.00     0.00     0.00     0.00]]

Now I want to use np.array change row 0 to look like, keeping the rest of the array constant:

 [[ 0.00     1.00     2.00     3.00     4.00]
  [ 0.00     0.00     0.00     0.00     0.00]
  [ 0.00     .....
1
  • pvfv=np.zeros((7,5)); pvfv[0,:] = np.array([i for i in range(pvfv.shape[1])]) Commented Apr 23, 2022 at 16:04

2 Answers 2

2

Simply use:

import numpy as np

n = 7
p = 5
zeros = np.zeros((n, p))
print("before: \n", zeros, "\n")

row = np.arange(0, p, dtype = float) #no need to copy but just to make things clear.
zeros[0] = row;
print("after: \n", zeros, "\n")

output:

before: 
[[0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]] 

after: 
[[0. 1. 2. 3. 4.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]] 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for helping me understand. Is adding the dtype =float necessary in all scenarios?
It doesn't matter in this case as the matrix entries (i.e. row 0) will be casted to the original type of the matrix e.g. numpy.float64.
0

You could do the top row and then stack it above the rest:

np.vstack((np.arange(5), np.zeros((6, 5))))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.