1

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 ?

1
  • 6
    Tuples in Python are immutable, you may need to use lists. Commented Oct 4, 2021 at 12:10

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Is there a way to reverse it after the replacement?
@jokerp Sure, you can cast all list into tuples later : list(map(tuple, list_of_list))
1

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.