ValueError: assignment destination is read-only [Solved]

avatar

Last updated: Apr 11, 2024 Reading time · 2 min

banner

# ValueError: assignment destination is read-only [Solved]

The NumPy "ValueError: assignment destination is read-only" occurs when you try to assign a value to a read-only array.

To solve the error, create a copy of the read-only array and modify the copy.

You can use the flags attribute to check if the array is WRITABLE .

Running the code sample produces the following output:

check if writeable

In your case, WRITEABLE will likely be set to False .

In older NumPy versions, you used to be able to set the flag to true by calling the setflags() method.

However, setting the WRITEABLE flag to True ( 1 ) will likely fail if the OWNDATA flag is set to False .

You will likely get the following error:

  • "ValueError: cannot set WRITEABLE flag to True of this array"

To solve the error, create a copy of the array when converting it from a Pillow Image to a NumPy array.

Passing the Pillow Image to the numpy.array() method creates a copy of the array.

You can also explicitly call the copy() method.

check if writable is set to true

You can also call the copy() method on the Pillow Image and modify the copy.

The image copy isn't read-only and allows assignment.

You can change the img_copy variable without getting the "assignment destination is read-only" error.

You can also use the numpy.copy() method.

The numpy.copy() method returns an array copy of the given object.

The only argument we passed to the method is the image.

You can safely modify the img_copy variable without running into issues.

You most likely don't want to make changes to the original image.

Creating a copy and modifying the copy should be your preferred approach.

If you got the error when using the np.asarray() method, try changing it to np.array() .

Change the following:

To the following:

As long as the WRITEABLE flag is set to True , you will be able to modify the array.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • TypeError: Object of type ndarray is not JSON serializable
  • ValueError: numpy.ndarray size changed, may indicate binary incompatibility
  • NumPy RuntimeWarning: divide by zero encountered in log10
  • ValueError: x and y must have same first dimension, but have shapes

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

极客教程 - 以工匠精神打磨精品教程

  • JavaScript 参考手册
  • Spring Boot
  • Spark Streaming
  • scikit-learn

Numpy中赋值目标为只读的错误 – 广播

在本文中,我们将介绍Numpy中的一个常见错误:“assignment destination is read-only”,它通常与广播有关。

阅读更多: Numpy 教程

Numpy中的广播是一种机制,它使得不同形状的数组在执行操作时具有相同的形状。例如,我们可以将一个标量(1维数组)加到一个矩阵(2维数组)中的每个元素,而无需将标量扩展为具有与矩阵相同的形状。将标量添加到矩阵的每个元素通常称为“标量广播”。

下面是标量广播的一个简单示例:

在这个示例中,我们把一个标量(b)加到一个矩阵(a)中。

但是,当我们尝试在广播期间复制值时,会出现“赋值目标是只读的”错误。让我们来看一个示例:

在这个示例中,我们将一个1维数组(b)分配给2维数组(a)中的一列。但是,当我们尝试进行此操作时,会出现“assignment destination is read-only”的错误。

这是因为我们尝试向只读的内存位置复制数据。在这个例子中,a的第一列被广播为与b相同的形状(2行1列,即2维数组),因此它变成只读的。

要解决这个问题,我们可以将代码稍微修改一下,使它在分配前将a复制到一个新的数组中:

在这个示例中,我们将a复制到c中,然后使用c来分配b的值,避免了“赋值目标是只读的”错误。

在Numpy中,广播是一种强大的机制,它使得不同形状的数组能够执行相同的操作。然而,在广播期间,我们需要注意将数据复制到新的数组中,以避免“赋值目标是只读的”错误。 Numpy中广播和标量广播的使用,可以更好的帮助我们编写高效、简洁的代码。

Python 教程

wxPython 教程

SymPy 教程

Matplotlib 教程

Web2py 教程

BeautifulSoup 教程

Java 教程

AngularJS 教程

TypeScript 教程

TypeScript 教程

WordPress 教程

WordPress 教程

Laravel 教程

PhantomJS 教程

Three.js 教程

Three.js 教程

Underscore.JS 教程

Underscore.JS 教程

WebGL 教程

PostgreSQL 教程

SQLite 教程

  • NumPy Ndarray 对象
  • NumPy 数组创建例程
  • NumPy 从现有数据创建数组
  • NumPy 数值范围的数组
  • NumPy 索引和切片
  • NumPy 数组操作 numpy.reshape
  • NumPy 数组操作 numpy.ndarray.flat
  • NumPy 数组操作 numpy.ndarray.flatten
  • NumPy 数组操作 numpy.ravel
  • NumPy 数组操作 numpy.transpose
  • NumPy 数组操作 numpy.ndarray.T
  • NumPy 数组操作 numpy.rollaxis
  • NumPy 数组操作 numpy.swapaxes
  • NumPy 数组操作 numpy.broadcast
  • NumPy 数组操作 numpy.broadcast_to
  • NumPy 数组操作 numpy.expand_dims
  • NumPy 数组操作 numpy.squeeze
  • NumPy 数组操作 numpy.concatenate
  • NumPy 数组操作 numpy.stack
  • NumPy 数组操作 numpy.hstack
  • NumPy 数组操作 numpy.vstack
  • NumPy 数组操作 numpy.split
  • NumPy 数组操作 numpy.hsplit
  • NumPy 数组操作 numpy.vsplit
  • NumPy 数组操作 numpy.resize
  • NumPy 数组操作 numpy.append
  • NumPy 数组操作 numpy.insert
  • NumPy 数组操作 numpy.delete
  • NumPy 数组操作 numpy.unique
  • NumPy 二进制运算符
  • NumPy 二进制位与运算符
  • NumPy 二进制位或运算符

NumPy: Make arrays immutable (read-only) with the WRITEABLE attribute

The NumPy array ( numpy.ndarray ) is mutable by default, which means you can update the values of its elements. By changing the settings of numpy.ndarray , you can make it immutable (read-only).

Making an array immutable can be useful for preventing accidental value updates.

This article covers the following topics.

The flags attribute stores memory layout information of ndarray

Make the ndarray immutable (read-only) with the writeable attribute, situations where the writeable attribute cannot be changed.

Keep in mind that if the original array is writable, you can still update the element values from the original array even if you make its view read-only, as discussed later.

The memory layout information of numpy.ndarray is stored in the flags attribute.

  • numpy.ndarray.flags — NumPy v1.24 Manual

The flags attribute returns an object of type numpy.flagsobj . You can access its attribute values using either the .attribute_name (lowercase) or ['ATTRIBUTE_NAME'] (uppercase) notation.

You can make the ndarray immutable (read-only) with the WRITEABLE attribute.

When you create a new numpy.ndarray , the WRITEABLE attribute is set to True by default, allowing you to update its values.

By setting the WRITEABLE attribute to False , the array becomes read-only, and attempting to update its values will result in an error.

You can change the WRITEABLE attribute using either .writeable or ['WRITEABLE'] , or you can alternatively change the setting with the setflags() method. In setflags() , the write argument corresponds to the WRITEABLE attribute.

  • numpy.ndarray.setflags — NumPy v1.24 Manual

The WRITEABLE attribute isn't always changeable.

For example, when you create a view of a numpy.ndarray array with a slice, if the original array is read-only ( WRITEABLE is False ), the view will also be read-only.

If the original array is read-only, you cannot change the WRITEABLE attribute of the view to True .

Even if you set the WRITEABLE attribute of the original array to True , the WRITEABLE attribute of the view remains False , but it becomes changeable to True .

If the WRITEABLE attribute of the original array is True , you can update the values from the original array even when the WRITEABLE attribute of the view is False .

In the case of a copy, a new array is created, so you can set the WRITEABLE attribute independently of the original array.

To determine whether an ndarray is a view or a copy and if it shares memory, refer to the following article:

  • NumPy: Determine if ndarray is view or copy and if it shares memory

Related Categories

Related articles.

  • Convert between pandas DataFrame/Series and NumPy array
  • NumPy: Broadcasting rules and examples
  • numpy.where(): Manipulate elements depending on conditions
  • NumPy: Extract or delete elements, rows, and columns that satisfy the conditions
  • NumPy: Add new dimensions to an array (np.newaxis, np.expand_dims)
  • NumPy: Split an array with np.split, np.vsplit, np.hsplit, etc.
  • Get image size (width, height) with Python, OpenCV, Pillow (PIL)
  • NumPy: Create an array with the same value (np.zeros, np.ones, np.full)
  • NumPy: squeeze() to remove dimensions of size 1 from an array
  • NumPy: Rotate array (np.rot90)
  • Matrix operations with NumPy in Python
  • NumPy: Save and load arrays in npy and npz files
  • Convert 1D array to 2D array in Python (numpy.ndarray, list)
  • Binarize image with Python, NumPy, OpenCV
  • How to fix "ValueError: The truth value ... is ambiguous" in NumPy, pandas

ProgrammerAH

Programmer guide, tips and tutorial, python numpy.ndarray valueerror:assignment destination is read-only.

reference resources: http://stackoverflow.com/questions/13572448/change-values-in-a-numpy-array

###################################################################3

Get the video stream from the raspberry pie camera and convert it to opencv format:

http://blog.csdn.net/u012005313/article/details/51482994

At the same time, you want to operate on each frame, but there is an error:

python numpy valueerror assignment destination is read only

ValueError:assignment destination is read-only

Images cannot be manipulated because they are read-only.

Find a way on stackhover: because in Python, the opencv image format is Numpy.ndarray You can modify the properties of ndarray by:

####################################################################

python numpy valueerror assignment destination is read only

Numpy.ndarray It has the following attributes:

C_ CONTIGUOUS(c_ contiguous)

F_ CONTIGUOUS(f_ contiguous)

OWNDATA(owndata)

WRITEABLE(writeable)

ALIGNED(aligned)

UPDATEIFCOPY(updateifcopy)

python numpy valueerror assignment destination is read only

The flags property is information about the array memory layout

Among them, the flags attribute can be modified in the form of a dictionary, for example:

You can also use lowercase attribute names:

Abbreviations (‘c ‘/’f’, etc.) are only used in dictionary form

python numpy valueerror assignment destination is read only

Only the attributes updateifcopy, writeable and aligned can be modified by users in three ways

1. Direct assignment:

2. Dictionary input:

3. Use function ndarray.setflags :

python numpy valueerror assignment destination is read only

  • Dataframe to numpy.ndarray Related issues of
  • AttributeError: ‘numpy.ndarray‘ object has no attribute ‘softmax‘
  • Python read / write file error valueerror: I/O operation on closed file
  • Pandas read_ Error in json() valueerror: training data
  • Tensorflow ValueError: Failed to convert a NumPy array to a Tensor
  • Python ValueError: only 2 non-keyword arguments accepted
  • C + + programming fault handling — error: assignment of read only data member ‘STD:: pair
  • Python error: local variable ‘XXXX’ referenced before assignment
  • Python UnboundLocalError: local variable ‘num’ referenced before assignment
  • Solving Python error: local variable ‘a’ referenced before assignment
  • Memory error in Python numpy matrix
  • No module named numpy error in Python code
  • Python_ Part 2 programming problems (3)_ solve numpy.core.multiarray Failed to import problem
  • Differences between shell script variable assignment and C language variable assignment
  • Warning when using numpy: runtimewarning: numpy.dtype size changed, may indicate binary incompatibility
  • UserWarning: Failed to initialize NumPy: No module named ‘numpy.core._multiarray_umath‘
  • Python error type error: ‘range’ object does not support item assignment, solution
  • Unable to call numpy in pychar, module notfounderror: no module named ‘numpy’
  • Assignment under multiple single edges is not supported for synthesis
  • Python3-ValueError:not enough values to unpack (expected 2, got 0)

Python Numpy.ndarray ValueError:assignment destination is read-only

python numpy valueerror assignment destination is read only

参考: http://stackoverflow.com/questions/13572448/change-values-in-a-numpy-array

问题 :img为numpy.ndarray,在使用img[img<0]=0 语句时,报错ValueError:assignment destination is read-only

(同一代码在win、ubuntu下没问题,而在centos7下报的错)

解决方案 :修改ndarray的属性:

python numpy valueerror assignment destination is read only

仅有属性UPDATEIFCOPY,WRITEABLE以及ALIGNED属性可以被使用者修改,有3种修改方式:

1.直接赋值:

2.字典输入:

3.使用函数ndarray.setflags:

python numpy valueerror assignment destination is read only

请填写红包祝福语或标题

python numpy valueerror assignment destination is read only

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

python numpy valueerror assignment destination is read only

Clayton Turner: An Introductory Guide

A blog dedicated to my experiences and development as a Data Science and Computer Science researcher.

Wednesday, June 10, 2015

Numpy valueerror: output array is read-only, no comments:, post a comment.

Valueerror assignment destination is read-only

One of the errors that developers often come across is the ValueError: assignment destination is read-only .

This error typically occurs when you try to modify a read-only object or variable.

What does the ValueError: assignment destination is read-only error mean?

How the error occurs.

Example 1: Modifying an Immutable Tuple

However, in Python, constants are typically immutable and cannot be modified once defined.

Therefore, this code will likely raise a valueerror .

Example 4: Altering an Immutable Data Structure

The code then changes the value associated with the ‘key’ to ‘ new_value ‘ by assigning it directly using indexing.

Solutions for ValueError: assignment destination is read-only

Solution 1: use mutable data structures.

Instead of using immutable data structures like tuples or strings, switch to mutable ones such as lists or dictionaries.

For example:

Solution 2: Reassign Variables

Solution 3: check documentation and restrictions.

It’s important to consult the documentation or source code to understand any restrictions required.

Solution 4: Use a Copy or Clone

If the object you’re working with is meant to be read-only, consider creating a copy or clone of it.

Solution 5: Identify Context-Specific Solutions

Understanding the possible cause will aid in finding a proper resolution.

Solution 6: Seek Help from the Community

Online forums, developer communities, and platforms like Stack Overflow can provide valuable insights and guidance from experienced programmers.

Frequently Asked Questions

To resolve this valueerror, you can apply different solutions such as using mutable data structures, reassigning variables, checking documentation and restrictions, using copies or clones, identifying context-specific solutions, or seeking help from the programming community.

Yes, there are similar errors that you may encounter in different programming languages. For example, in JavaScript, you might encounter the error TypeError: Assignment to a constant variable when trying to modify a constant.

By following the solutions provided in this article, such as using mutable data structures, reassigning variables, checking restrictions, making copies or clones, considering context-specific solutions, and seeking community help, you can effectively resolve this error.

Additional Resources

Leave a comment cancel reply.

pythoneo

Online How to Python stuff

How to create an immutable Numpy array?

An immutable array is read-only, meaning you cannot modify its elements once it’s defined. This can be useful when you want to ensure data integrity or prevent accidental changes to the array.

Numpy immutable array

Setting writeable flag

To make the array immutable, you need to set the writable flag to False.

As demonstrated, attempting to modify the array after setting the writable flag to False results in a Python ValueError, indicating the array is read-only.

Setting a writeable flag rendered your code immutable. To turn off read-only mode , you need to set the writeable flag back to true.

Setting the write flag

Alternatively, you can use the setflags method to make the array immutable by setting write to False.

Python displays ValueError as well. The full error message is as follows:

Set the write flag back to true to allow editing.

By creating an immutable NumPy array, you can ensure data consistency and prevent unintended modifications, making it a valuable tool for various data manipulation and analysis tasks in Python.

Determine how a param is being set as readonly

I have a class similar to the example below

I’m using this basic example to test the usage pattern where I store a numpy.ndarray once but keep both a numpy recarray and pandas Dataframe view of the same data to allow for different access patterns a viewing with panel without duplicating the large array in memory.

this example works as you can see from the example below

However I have this same basic pattern in a much larger class but when I try to assign a value to the main numpy array I get a ValueError: assignment destination is read-only . I have not declared any of the paramerters in param.Parameterized class as readonly or constant but continue to get this simple ValueError.

Is there a way to track down were the readonly designation is being applied via some other more detailed stack trace? I’m beyond frustrated with trying ot figure out why the main array is being assigned as readonly when I have made no such designation in my code.

I have found the source of my error. It appears this is an issue associated with reading numpy arrays from a buffer not with the parameters themselves.

Hopefully this helps someone avoid a couple of days of frustrating searching in the future.

If you read a numpy array in from a buffer and would like to manipulate the values across views add a .copy() to the end of the initial read so that the array is not set as read-only.

Just out of curiosity, did the error message ( ValueError: assignment ... ) have anything to do with Param itself?

No. I have been really impressed with param so I’m rewriting my old code into param.Parameterized classes to better document the purpose of the code and to take advantage of the visualization capabilities of panel. One of the features I was using in Jupyter as I get better at parm and panel was the with param.exceptions_summarized(): context manager.

I mistakenly thought this context manager would only summarize the param related exceptions since the code was previously working as non-param classes. The ValueError was the only thing being dumped out so I assumed it was a param related error. Once I removed the context manager and explored the full trace I found the numpy related issue. This more a gap in my understanding than a real issue with any one library.

Thanks for all the help. My 2022 resolution is to get all my code into param and panel related classes so I’m sure I will be pestering everyone with issues that may end up being more me than the libraries themselves. Merry Christmas!

:wink:

I believe exceptions_summarized was added to param purely to write the documentation, it’s useful to only print the error message of an instead long and boring exception traceback, exception that would stop the notebook execution. But in your code you should definitely not use it since it will skip exceptions. This context manager would be better off in a separate module dedicated to the docs.

System error: assignment destination is read-only

  • High: It blocks me to complete my task.

I would like to ask about an issue that I encountered when I try to distribute my work on multiple cpu nodes using ray.

My input file is a simulation file consisting of multiple time frames, so I would like to distribute the calculation of one frame to one task. It works fine when I just used pool from the multiprocessing python library, where only one node (128 tasks in total) can be used. Since I have more than 2,000 time frames, I would like to use multiple nodes in this calculation, and the multiprocessing python library isn’t the best choice.

I created my code using this template: ray/simple-trainer.py at master · ray-project/ray · GitHub . Here’s a brief summary of my code:

import socket import sys import time import ray

@ray.remote def hydration_water_calculation2(t, u): # in one frame return xyz

ray.init(address=os.environ[“ip_head”])

print(“Nodes in the Ray cluster:”) print(ray.nodes())

for i in frame_values: ip_addresses = ray.get([hydration_water_calculation2.remote(i, u0) for _ in range(1)]) print(Counter(ip_addresses))

But I got the following error: Traceback (most recent call last): File “…/…/hydration_whole_global2_ray.py”, line 269, in ip_addresses = ray.get([hydration_water_calculation2.remote(i, u0) for _ in range(1)]) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/_private/client_mode_hook.py”, line 105, in wrapper return func(*args, **kwargs) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/worker.py”, line 1809, in get raise value.as_instanceof_cause() ray.exceptions.RayTaskError: ray::hydration_water_calculation2() (pid=27283, ip=10.8.9.236) At least one of the input arguments for this task could not be computed: ray.exceptions.RaySystemError: System error: assignment destination is read-only traceback: Traceback (most recent call last): File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/serialization.py”, line 332, in deserialize_objects obj = self._deserialize_object(data, metadata, object_ref) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/serialization.py”, line 235, in _deserialize_object return self._deserialize_msgpack_data(data, metadata_fields) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/serialization.py”, line 190, in _deserialize_msgpack_data python_objects = self._deserialize_pickle5_data(pickle5_data) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/serialization.py”, line 178, in _deserialize_pickle5_data obj = pickle.loads(in_band, buffers=buffers) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 2106, in setstate self[self.ts.frame] File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 1610, in getitem return self._read_frame_with_aux(frame) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 1642, in _read_frame_with_aux ts = self._read_frame(frame) # pylint: disable=assignment-from-no-return File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/XDR.py”, line 255, in _read_frame timestep = self._read_next_timestep() File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/XDR.py”, line 273, in _read_next_timestep self._frame_to_ts(frame, ts) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/XTC.py”, line 144, in _frame_to_ts ts.dimensions = triclinic_box(*frame.box) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 810, in dimensions self._unitcell[:] = box ValueError: assignment destination is read-only (hydration_water_calculation2 pid=27283) 2022-05-01 22:53:55,714 ERROR serialization.py:334 – assignment destination is read-only (hydration_water_calculation2 pid=27283) Traceback (most recent call last): (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/serialization.py”, line 332, in deserialize_objects (hydration_water_calculation2 pid=27283) obj = self._deserialize_object(data, metadata, object_ref) (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/serialization.py”, line 235, in _deserialize_object (hydration_water_calculation2 pid=27283) return self._deserialize_msgpack_data(data, metadata_fields) (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/serialization.py”, line 190, in _deserialize_msgpack_data (hydration_water_calculation2 pid=27283) python_objects = self._deserialize_pickle5_data(pickle5_data) (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/serialization.py”, line 178, in _deserialize_pickle5_data (hydration_water_calculation2 pid=27283) obj = pickle.loads(in_band, buffers=buffers) (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 2106, in setstate (hydration_water_calculation2 pid=27283) self[self.ts.frame] (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 1610, in getitem (hydration_water_calculation2 pid=27283) return self._read_frame_with_aux(frame) (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 1642, in _read_frame_with_aux (hydration_water_calculation2 pid=27283) ts = self._read_frame(frame) # pylint: disable=assignment-from-no-return (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/XDR.py”, line 255, in _read_frame (hydration_water_calculation2 pid=27283) timestep = self._read_next_timestep() (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/XDR.py”, line 273, in _read_next_timestep (hydration_water_calculation2 pid=27283) self._frame_to_ts(frame, ts) (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/XTC.py”, line 144, in _frame_to_ts (hydration_water_calculation2 pid=27283) ts.dimensions = triclinic_box(*frame.box) (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 810, in dimensions (hydration_water_calculation2 pid=27283) self._unitcell[:] = box (hydration_water_calculation2 pid=27283) ValueError: assignment destination is read-only

Could anyone help me diagnose the issue? I’m new to ray and still learning why I was getting the “assignment destination is read-only” error. Many thanks in advance!

Hey @Chengeng-Yang , the read-only errors are happening because Ray stores arguments in the shared memory object store. This allows arguments to be shared with process very efficiently with zero memory copies, but has a side-effect of rendering numpy arrays immutable.

In this case, it seems that during setstate for your program an assignment is made that will update an existing array. Is it possible to modify the code around there to make a copy of the array prior to calling self._unitcell[:] = box ? I.e., self._unitcell = self._unitcell.copy(); self._unitcell[:] = box . That should fix the deserialization problem.

Reference stack line: File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 2106, in setstate

Hi @ericl , many thanks for your help! Your suggestion DID work. The deserialization issue has been fixed after I made a copy of self._unitcell.

Thanks again and have a wonderful day :))

Related Topics

Topic Replies Views Activity
0 355 August 14, 2023
Ray Core 4 699 July 8, 2021
Ray Core 5 316 August 25, 2022
Ray Core 1 606 March 10, 2021
Ray Core 2 831 November 30, 2022
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Trying to replace part of array to another array, get error ValueError: assignment destination is read-only

I have two arrays with pixels, I need to replace the first part of array 'pixels_new', to array 'pixels_old'

It gives me an error:

Please help me with it

Nikolas's user avatar

  • asarray doesn't make a copy if the source is already an array, –  hpaulj Commented Dec 2, 2020 at 16:18

2 Answers 2

I did a simple test as below.

This shows np.asarray does not return the immutable variable, which is read-only. The error is ValueError: assignment destination is read-only . So, I think your im and img variables are immutable. You haven't included the source code for your im and img , so I couldn't tell much about this. However, I have one suggestion is that you should clone or convert your im and img into nd.array before proccessing.

Hung Du's user avatar

When we see this message :‍‍‍ ValueError: assignment destination is read-only

We need to take two steps to solve it:

The problem will be solved, but if the following message is given, do the following:

ValueError: cannot set WRITEABLE flag to True of this array

Make a copy of it so you can apply the changes to it:

Seyed_Ali_Mohtarami's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

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

Not the answer you're looking for? Browse other questions tagged python numpy or ask your own question .

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • Manuscript rejected after all reviewers indicate it is "good match" to publish in journal. Is this common?
  • How to express degrees of understanding in Chinese:
  • If Venus had a sapient civilisation similar to our own prior to global resurfacing, would we know it?
  • Zsh: Copy or Move symlinks to regular files, but not symlinks to directories (or vice versa)
  • What is this houseplant with a red fleshy stem and thick waxy leaves?
  • Did the United States have consent from Texas to cede a piece of land that was part of Texas?
  • Erase the loops
  • Can police offer an “immune interview”?
  • Has technology regressed in the Alien universe?
  • Is there a French noun equivalent for "twofer"?
  • Venus’ LIP period starts today, can we save the Venusians?
  • Questions about best way to raise the handlebar on my bike
  • Guitar amplifier placement for live band
  • Unexpected behaviour during implicit conversion in C
  • Is the Ted-Ed Leprechaun's Magic Bag Unique?
  • What connotation does "break out the checkbook" have?
  • How to handle stealth before combat starts?
  • Output of a Diffractometer
  • Are all simple groups of order coprime to 3 cyclic? If so, why?
  • How predictable are the voting records of members of the US legislative branch?
  • Why would Space Colonies even want to secede?
  • What is the purpose of toroidal magnetic field in tokamak fusion device?
  • Making wobbly 6x4’ table stable
  • DIN Rail Logic Gate

python numpy valueerror assignment destination is read only

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Xarray operations produce read-only array #3813

@djhoese

djhoese commented Feb 28, 2020

I've turned on testing my Satpy package with unstable or pre-releases of some of our dependencies including numpy and xarray. I've found one error so far where in previous versions of xarray it was possible to assign to the numpy array taken from a DataArray.

numpy as np import dask.array as da import xarray as xr data = np.arange(15, 301, 15).reshape(2, 10) data_arr = xr.DataArray(data, dims=('y', 'x'), attrs={'test': 'test'}) data_arr = data_arr.copy() data_arr = data_arr.expand_dims('bands') data_arr['bands'] = ['L'] n_arr = np.asarray(data_arr.data) n_arr[n_arr == 45] = 5

Which results in:

A writable array. No error.

If this is expected new behavior then so be it, but wanted to check with the xarray devs before I tried to work around it.

@max-sixty

max-sixty commented Feb 28, 2020

Thanks for the report . Confirmed in 0.15.0 too.

Do you know which of those steps causes the array to become non-writeable?

Sorry, something went wrong.

@dcherian

dcherian commented Feb 29, 2020 • edited Loading

It's usually .

We should add an FAQ for little things like this.

max-sixty commented Feb 29, 2020

djhoese commented Feb 29, 2020

That's exactly it. What's really weird for this is that the original code in Satpy is using a dask array and not a numpy array. It seemed very strange to both copy the DataArray ( ), convert the dask array to a numpy array ( ), and then still get a read-only array.

I can understand how xarray would treat numpy arrays and dask arrays the same when it comes to this, but coming from outside the project it is very surprising that a dask array would be marked as read-only when it was used to just create a "new" numpy array.

Feel free to close this or use it as a marker to clarify some documentation or error messages as mentioned in .

Cheers

Yes, let's leave this open. Two follow-ups from ; we would welcome PRs:

in the error message xarray prints when an array is read-only.

argument to , so users can write if they want a writeable result.

@djhoese

bradyrx commented Jul 7, 2020

FYI, this is also seen on , but only when . It seems like ndarrays write switch are turned off when . This is also solved by , which is good anways to avoid mutating the original ndarrays. Perhaps also a could be added to to create copies of the ndarrays? I'd be happy to lead that PR if it makes sense.

Example:

match_nans(a, b): """Pairwise matching of nans between two time series.""" # Try with and without `.copy` commands. # a = a.copy() # b = b.copy() if np.isnan(a).any() or np.isnan(b).any(): idx = np.logical_or(np.isnan(a), np.isnan(b)) a[idx], b[idx] = np.nan, np.nan return a, b A = xr.DataArray(np.random.rand(10, 5), dims=['time', 'space']) B = xr.DataArray(np.random.rand(10, 5), dims=['time', 'space']) A[0, 1] = np.nan B[5, 0] = np.nan xr.apply_ufunc(match_nans, A, B, input_core_dims=[['time'], ['time']], output_core_dims=[['time'], ['time']], # Try with and without vectorize. vectorize=True,)
  • 👍 2 reactions

@rbavery

rbavery commented Mar 30, 2021

I ran into the same issue as with writable arrays and apply_ufunc. An addition to the docs FAQ or apply_ufunc docs would help clarify that you can't write to the array inputs in the ufunc. I also want to +1 's idea of making an arg to apply_ufunc that copies the input arrays to handle this common use case.

@AlxLhrNc

No branches or pull requests

@djhoese

IMAGES

  1. Python Numpy.ndarray ValueError:assignment destination is read-only

    python numpy valueerror assignment destination is read only

  2. Python Numpy.ndarray ValueError:assignment destination is read-only

    python numpy valueerror assignment destination is read only

  3. Python Numpy.ndarray ValueError:assignment destination is read-only

    python numpy valueerror assignment destination is read only

  4. Python Numpy.ndarray ValueError:assignment destination is read-only

    python numpy valueerror assignment destination is read only

  5. ValueError: assignment destination is read-only · Issue #14972 · numpy

    python numpy valueerror assignment destination is read only

  6. Valueerror Assignment Destination Is Read Only

    python numpy valueerror assignment destination is read only

COMMENTS

  1. Numpy: assignment destination is read-only

    Numpy: assignment destination is read-only - broadcast. Ask Question Asked 6 years, 4 months ago. ... ValueError: assignment destination is read-only I can't change the rgb image! python; numpy; array-broadcasting; Share. Follow asked Apr 5, 2018 at 13:38. ...

  2. ValueError: assignment destination is read-only [Solved]

    The NumPy "ValueError: assignment destination is read-only" occurs when you try to assign a value to a read-only array. To solve the error, create a copy of the read-only array and modify the copy. You can use the flags attribute to check if the array is WRITABLE. main.py. from PIL import Image.

  3. python

    Since numpy version 1.16.0 the following doesn't work anymore:. img = np.asarray(Image.open(filename)) img.setflags(write=1) The problem is that now OWNDATA is set to False and you can't set WRITEABLE flag to True.Therefore you should simply do the following: img = np.array(Image.open(filename))

  4. Numpy中赋值目标为只读的错误

    Numpy中赋值目标为只读的错误 - 广播 在本文中,我们将介绍Numpy中的一个常见错误:"assignment destination is read-only",它通常与广播有关。 阅读更多:Numpy 教程 广播 Numpy中的广播是一种机制,它使得不同形状的数组在执行操作时具有相同的形状。例如,我们可以将一个标量(1维数组)加到一个矩阵 ...

  5. NumPy: Make arrays immutable (read-only) with the WRITEABLE attribute

    You can make the ndarray immutable (read-only) with the WRITEABLE attribute. When you create a new numpy.ndarray, the WRITEABLE attribute is set to True by default, allowing you to update its values. a[0] = 100 print(a) # [100 1 2] source: numpy_flags.py. By setting the WRITEABLE attribute to False, the array becomes read-only, and attempting ...

  6. ValueError: assignment destination is read-only #6242

    ValueError: assignment destination is read-only #6242. Closed T-chuangxin opened this issue Feb ... assignment destination is read-only ` The text was updated successfully, but these errors were encountered: ... bensdm commented Feb 22, 2019 • edited Loading. this is due to numpy version <1.16, you can fix it by adding before line 130: image ...

  7. ValueError: assignment destination is read-only, when ...

    When I run SparseCoder with n_jobs > 1, there is a chance to raise exception ValueError: assignment destination is read-only. The code is shown as follow: from sklearn.decomposition import SparseCoder import numpy as np data_dims = 4103 ...

  8. Python Numpy.ndarray ValueError:assignment destination is read-only

    ValueError:assignment destination is read-only. Images cannot be manipulated because they are read-only. Find a way on stackhover: because in Python, the opencv image format is Numpy.ndarray You can modify the properties of ndarray by: img.flags.writeable = True ##### Numpy.ndarray It has the following attributes: C_ CONTIGUOUS(c_ contiguous)

  9. Deep Dive into Pandas Copy-on-Write Mode

    to_numpy and .values will return a read-only array because of this. This means that the resulting array is not writeable. df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) arr = df.to_numpy() arr[0, 0] = 1. This will trigger a ValueError: ValueError: assignment destination is read-only. You can avoid this in two different ways:

  10. Python Numpy.ndarray ValueError:assignment destination is read-only

    问题:img为numpy.ndarray,在使用img[img<0]=0 语句时,报错ValueError:assignment destination is read-only (同一代码在win、ubuntu下没问题,而在centos7下报的错) 解决方案:修改ndarray的属性: img.flags.writeable = True 补充:查看ndarray的属性 import numpy as np help(np.ndarray.flags)

  11. " ValueError: assignment destination is read-only" when using Pandas

    System information Have I written custom code (as opposed to using a stock example script provided in TensorFlow): Custom code I suppose (see below) OS Platform and Distribution (e.g., Linux Ubuntu...

  12. Numpy ValueError: Output array is read-only

    import numpy as np a = np.arange(6) a.setflags(write=False) a[2] = 42 ValueError:assignment destination is read-only This is intended behavior. I am currently working on a neural network which utilizes gradient descent and updates through the use of a client-server relationship.

  13. [SOLVED] Valueerror assignment destination is read-only

    Solutions for ValueError: assignment destination is read-only. Here are some solutions to solve the ValueError: assignment destination is read-only: Solution 1: Use Mutable Data Structures. Instead of using immutable data structures like tuples or strings, switch to mutable ones such as lists or dictionaries.

  14. How to create an immutable Numpy array?

    Traceback (most recent call last): File "C:\Users\pythoneo\PycharmProjects\pythoneoProject\immutable_array_python.py", line 11, in my_array[2] = 6 ValueError: assignment destination is read-only Setting a writeable flag rendered your code immutable. To turn off read-only mode, you need to set the writeable flag back to true.

  15. python

    I got stuck practising with images in Python 3: import numpy as np from matplotlib.image import imread photo_data = imread('c:\jpeg.jpg') photo_data[0,0,1] = 0 ... [0,0,1] = 0 4 plt.imshow(photo_data) ValueError: assignment destination is read-only ... The issue at hand is that the array is set by matplotlib to read-only. To confirm: print ...

  16. Determine how a param is being set as readonly

    But in your code you should definitely not use it since it will skip exceptions. This context manager would be better off in a separate module dedicated to the docs. I have a class similar to the example below class P (param.Parameterized): a = param.Array () r = param.Array () d = param.DataFrame () def setup (self): axis_names = [f"Axis_ {i+1 ...

  17. System error: assignment destination is read-only

    It works fine when I just used pool from the multiprocessing python library, where only one node (128 tasks in total) can be used. Since I have more than 2,000 time frames, I would like to use multiple nodes in this calculation, and the multiprocessing python library isn't the best choice. ... ValueError: assignment destination is read-only ...

  18. python

    ValueError: assignment destination is read-only I guess that's because I can't really write into a numpy array. P.S. The actual size of the numpy array is 514 by 504 and of the list is 8. ... Read-only array in numpy can be made writable: nArray.flags.writeable = True ... python; numpy; indexing;

  19. [ray] numpy arrays become read-only, and no copy on write ...

    ValueError: assignment destination is read-only Describe the problem numpy objects are (intentionally) read-only when retrieved from the object store via ray.get, as described in the documentation .

  20. python

    Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company Visit the blog

  21. Xarray operations produce read-only array #3813

    It seemed very strange to both copy the DataArray (.copy()), convert the dask array to a numpy array (np.asarray), and then still get a read-only array. I can understand how xarray would treat numpy arrays and dask arrays the same when it comes to this, but coming from outside the project it is very surprising that a dask array would be marked ...