2

I would like to know is there an "easy" way to create two matching arrays inserting some dummy missing value in both arrays so they remain same size and indexes that are the same in both arrays remain the same, so for example:

["A", "B", "C", "D", "E", "F"] and ["B", "C", "E"]

Would be

["A", "B", "C", "D", "E", "F"] and ["N/A", "B", "C", "N/A", "E", "N/A"]

Thanks in advance :-)

3
  • There are no 'easy ways', there are algorithms that do stuff. Have you tried writing such an algorithm to solve the problem? If yes, please show your code. Commented Jan 24, 2017 at 12:58
  • Helo ForceBru, maybe I miss-spoken, i have solved the problem: a = [1,2,3,4,5] b = [1,3,5] c = [] for el in a: if el in b: c.append (el) else: c.append (0) print (c) Commented Jan 24, 2017 at 13:00
  • 1
    please don't post code in the comments, add it to the question instead. Commented Jan 24, 2017 at 13:04

2 Answers 2

7

One-liner in a list comprehension to do this:

array_1 = ["A", "B", "C", "D", "E", "F"]
array_2 = {"B", "C", "E"}

array_3 = [x if x in array_2 else "N/A" for x in array_1]

print(array_3)

result:

['N/A', 'B', 'C', 'N/A', 'E', 'N/A']

Note that I converted array_2 to a set for quicker lookup.

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

Comments

4
array_1 = ["A", "B", "C", "D", "E", "F"] 
array_2 = ["B", "C", "E"]

array_3 = array_1

for n,x in enumerate(array_3):

    if x not in array_2:

        array_3[n] = np.nan

print (array_3)

out:

[nan, 'B', 'C', nan, 'E', nan]

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.