简体   繁体   中英

Python numpy array assign values to each column according to row

I want to assign row-specific values to each row in a 2D numpy array. In particular, each row should contain the value of the reciprocal of its row number. In other words, all columns in row 1 should have values 1, all columns in row 2 should be 1/2, all in row 3 should be 1/3, and so on. I tried this:

m = 3
n = 10

train = np.empty([n,m], float)

for curr_n in range(n):
    train[curr_n,:] = 1/(curr_n+1)

print train

But the output is:

[[ 1.  1.  1.]
 [ 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.]]

What am I doing wrong? I used "float" at the beginning, but I'm still getting solid 0 integers for all but the first row.

Implicit type conversion has been added in Python 3, so your original code will then work, as is:

from __future__ import division

m = 3
n = 10

train = np.empty([n,m], float)

for curr_n in range(n):
   train[curr_n,:] = 1/(curr_n+1)

print train

Some information on the __future__ module can be seen in the official docs future module

Or, as sshashank124 put in his answer and I put in the comment, you can use 1. or 1.0 to force float behavior.

You have a simple type problem. Use 1.0 instead of 1 in your reciprocation. The following works:

m = 3
n = 10

train = np.empty([n,m])

for curr_n in range(n):
    train[curr_n,:] = 1.0/(curr_n+1)   #converted 1 to 1.0

print train

Explanation

Although you might think that numpy deals with floats by default, in this case, the numpy array is getting assigned the value after python has had the time to calculate the inverses. It is then that python truncates your floats to an int and numpy innocently converts that sneaky int to a float just as it is supposed to and ends up taking all the blame .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM