Home > front end >  Can't replace an array inside a tuple with another array of same size - Python
Can't replace an array inside a tuple with another array of same size - Python

Time:10-05

I have a list of tuples:

enter image description here

I want to replace the second np.array of the first tuple with an array of the same length but filled with zeros:

I have tried the following:

Coeff[0][1] =np.zeros(len(Coeff[0][1]))

But I get the:

'tuple' object does not support item assignment

Any idea how to complete the replacement process ?

CodePudding user response:

Tuples are immutable in Python, you cannot change values stored in it.

You can do list(map(list, list_of_tuples)) for a quick casting into list, or [list(x) for x in list_of_tuples] if you want to use list comprehension.

I've done some ugly %timeit benchmark on my computer, both seems merely equivalent in speed.

CodePudding user response:

If you do not need to keep the original values in the arrays, then you could use numpy.nan_to_num() with copy=False to modify the second array in the tuple in-place. This has the advantage of not creating new arrays.

The following example replaces the second array of every tuple in Coeff with zeros.

import numpy as np

Coeff = [
    tuple(np.full((5, ), np.nan) for i in range(2))
    for j in range(5)
]
print(Coeff)

nil = [np.nan_to_num(tup[1], copy=False) for tup in Coeff]
print(Coeff)

The output is

[
    (array([nan, nan, nan, nan, nan]), array([nan, nan, nan, nan, nan])),
    (array([nan, nan, nan, nan, nan]), array([nan, nan, nan, nan, nan])),
    (array([nan, nan, nan, nan, nan]), array([nan, nan, nan, nan, nan])),
    (array([nan, nan, nan, nan, nan]), array([nan, nan, nan, nan, nan])), 
    (array([nan, nan, nan, nan, nan]), array([nan, nan, nan, nan, nan]))
]
[
    (array([nan, nan, nan, nan, nan]), array([0., 0., 0., 0., 0.])),
    (array([nan, nan, nan, nan, nan]), array([0., 0., 0., 0., 0.])),
    (array([nan, nan, nan, nan, nan]), array([0., 0., 0., 0., 0.])),
    (array([nan, nan, nan, nan, nan]), array([0., 0., 0., 0., 0.])),
    (array([nan, nan, nan, nan, nan]), array([0., 0., 0., 0., 0.]))
]

If you only need the work with the first tuple, you could use nil = np.nan_to_num(Coeff[0][1], copy=False). Note that I use nil to indicate you do not need the result of the function.

  • Related