简体   繁体   English

Python 中的二维数组切片和替换值

[英]2D array slicing and replacing vlaues in Python

I have a 2D array, and its size is based on a variable.我有一个二维数组,它的大小基于一个变量。 I would like to change the values of specific rows and columns based on an equation.我想根据方程式更改特定行和列的值。

For example:例如:

import numpy as np

size = 6
weight = np.ones([size, size])
weight[size / 6 * 2:size / 6 * 4 + 1, :] = 5

print(weight)

But I got an error:但我得到一个错误:

TypeError: slice indices must be integers or None or have an __index__ method

I think size / 6 * 2 and size / 6 * 4 are integers.我认为size / 6 * 2size / 6 * 4是整数。

How can I fix it?我该如何解决?

And if I have to set size / 6 equal to float , for example, 7 / 6 , how can I write a code to make 7 / 6 into the closest integer to avoid the error shown above?如果我必须将size / 6设置为float ,例如7 / 6 ,我该如何编写代码使7 / 6成为最接近的 integer 以避免上面显示的错误?

Python supports two types of division natively. Python 原生支持两种除法。 Floor division is performed with // , and always results in an int .地板除法是用//执行的,并且总是导致int True division is performed with / and always results in a float .真正的除法是用/执行的,并且总是产生一个float

You can check with the following:您可以检查以下内容:

>>> size = 6
>>> type(size / 6)
float
>>> type(size // 6)
int
>>> size / 6 == size // 6
True

So the simplest way is to write:所以最简单的方法是写:

weight[size // 6 * 2:size // 6 * 4 + 1, :] = 5

Alternatively, you can make the cast explicit, although this is less efficient:或者,您可以使强制转换显式,尽管这样效率较低:

weight[int(size / 6) * 2:int(size / 6) * 4 + 1, :] = 5

By the way, if you want to do a ceiling divide, just add (6 - 1) = 5 and do floor divide:顺便说一句,如果你想做一个上限除法,只需添加(6 - 1) = 5并做下限除法:

weight[(size + 5) // 6 * 2:(size + 5) // 6 * 4 + 1, :] = 5

If you want to round, add 6 / 2 = 3.0 and do floor divide:如果要四舍五入,请添加6 / 2 = 3.0并进行除数:

weight[(size + 3) // 6 * 2:(size + 3) // 6 * 4 + 1, :] = 5

And of course you can round explicitly:当然你可以明确地四舍五入:

weight[round(size / 6 * 2):round(size / 6 * 4) + 1, :] = 5

All of these options will work for values of size that are non-integer multiples of 6.所有这些选项都适用于size为 6 的非整数倍数的值。

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

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