简体   繁体   English

Python numpy数组根据行为每一列赋值

[英]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.我想为二维 numpy 数组中的每一行分配特定于行的值。 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.换句话说,第 1 行中的所有列的值都应该是 1,第 2 行中的所有列都应该是 1/2,第 3 行中的所有列都应该是 1/3,依此类推。 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.我在开始时使用了“float”,但除了第一行之外,我仍然得到了实心 0 整数。

Implicit type conversion has been added in Python 3, so your original code will then work, as is: Python 3 中添加了隐式类型转换,因此您的原始代码将可以正常工作,如下所示:

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关于__future__模块的一些信息可以在官方文档future 模块中看到

Or, as sshashank124 put in his answer and I put in the comment, you can use 1. or 1.0 to force float behavior.或者,正如 sshashank124 在他的回答中和我在评论中所说的那样,您可以使用 1. 或 1.0 来强制浮动行为。

You have a simple type problem.你有一个简单的type问题。 Use 1.0 instead of 1 in your reciprocation.在您的往复中使用1.0而不是1 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.尽管您可能认为 numpy 默认处理浮点数,但在这种情况下,python 有时间计算逆数之后,numpy 数组被分配了值。 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 .然后, python将您的浮点数截断为一个 int,而 numpy 无辜地将那个偷偷摸摸的int转换为一个float ,正如它应该的那样,并最终承担所有责任

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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