T
T
Timebird2018-03-06 23:21:18
Python
Timebird, 2018-03-06 23:21:18

How to replace some array values?

The question may seem cumbersome, but it is very simple.
I have two arrays: a1and a2. In the array a1, all elements of type int, in the array a2there are both int and str (in random order, they are scattered there).
If you write , then the output is something like this:for i in list(zip(a1, a2)): print(i)

...
(array([ 1.]), array([ nan]))
(array([ 1.]), array([ 2.]))
(array([ 2.]), array([ nan]))
(array([ 1.]), array([ nan]))
(array([ 2.]), array([ 1.]))
...

I want that in case the second element of the pair is an integer, then the first element of the pair is replaced by the second element of the pair. If we draw an analogy with the example above, then the output is expected to be:
array([ 1.]
      [ 2.]
      [ 2.]
      [ 1.]
      [ 1.])

I tried to write the following code, it doesn't work (it doesn't throw any errors, but it doesn't actually change anything):
for i in list(zip(a1, a2)):
    if isinstance(i[1], int):
        i[0] == i[1]

List comprehensions produces the same result.
a3 = [i[0] == i[1] for i in list(zip(a1, a2)) if isinsance(i[1], int)]

How to write correctly and what is my mistake?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Pugachev, 2018-03-06
@Timebird

Timebird
is not suitable?

for i, e in enumerate(a2):
    if isinstance(e, int):
        a1[i] = e

(I did not run the code if cho)

A
aRegius, 2018-03-07
@aRegius

what's my mistake?

1. Fatigue, most likely. This is the explanation for your use of the == comparison operator instead of the assignment operator.
2. But even in this case:
a) Cycle. Python will not let you change one of the elements of the tuple.
b) List generator. Python basically won't allow you to use the assignment operator.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question