0

I am writing a program to concatenate two numpy arrays and I want the program to print a message for each possible outcome (horizontal, vertical, or no concatenation). I have the following code and I don´t understand why even when the first condition (np.hstack) is met it continues evaluating the subsequent if and else statements and wrongly prints that there is both a horizontal concatenation (first condition is met) and that a concatenation is not possible.

import numpy as np
def fun1(a,b):
    if a.shape[0] == b.shape[0]:
        print("The horizontal concatenation is:", np.hstack((a,b)))
    if a.shape[1] == b.shape[1]:
        print("The vertical concatenation is:", np.vstack((a,b)))
    else:
        print("These arrays cannot be concatenated.")

a = np.floor(10*np.random.random((3,2)))
b = np.floor(10*np.random.random((3,4)))
fun1(a,b)

Output:

The horizontal concatenation is: [[5. 0. 1. 1. 3. 7.]
                                  [4. 1. 8. 3. 1. 9.]
                                  [9. 1. 5. 7. 0. 0.]]
These arrays cannot be concatenated.
4
  • 1
    Your second if should probably be an elif. As it reads now you have two separate if statements. Commented Feb 14, 2019 at 21:54
  • 1
    The if/else structure is insufficient. To avoid the wrong message you would need if/elif/else as written. But this does not cover the case when both concatenations are possible. Commented Feb 14, 2019 at 21:55
  • @mkiver thanks, I corrected it with an elif instead of the second if and now it works. However, I had not considered the case when there is a "perfect" concatenation on both axes - is there a convention that says which axis takes priority then? Commented Feb 14, 2019 at 22:00
  • 1
    @Madrid_datalady See my answer. With 3 if statements both horizontal and vertical concatenation would be printed. Commented Feb 14, 2019 at 22:06

1 Answer 1

1

Instead of the else part you need a third if statement with this condition:

if a.shape[0] == b.shape[0]:
    print("The horizontal concatenation is:", np.hstack((a,b)))
if a.shape[1] == b.shape[1]:
    print("The vertical concatenation is:", np.vstack((a,b)))
if a.shape[0] != b.shape[0] and a.shape[1] != b.shape[1]:
    print("These arrays cannot be concatenated.")
Sign up to request clarification or add additional context in comments.

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.