<jupyter_start><jupyter_text>Simply put, the newaxis is used to increase the dimension of the existing array by one more dimension, when used once. Thus,1D array will become 2D array2D array will become 3D array3D array will become 4D array and so on..Example:Let's say you want to add the following two arrays: x1 = np.array([1, 2, 3, 4, 5]) x2 = np.array([5, 4, 3])If you try to add these just like that, numpy will raise the following ValueError :ValueError: operands could not be broadcast together with shapes (5,) (3,)In this situation, you can use np.newaxis to increase the dimension of one of the arrays so that numpy can broadcast.<jupyter_code>x1,x2
x1_new = x1[:, np.newaxis]
x1_new,x1
x1_new + x2<jupyter_output><empty_output><jupyter_text>Alternatively, you can also add new axis to the array x2:<jupyter_code>x2_new = x2[:, np.newaxis]
x2_new
x1
x1+x2_new<jupyter_output><empty_output><jupyter_text>Note: Observe that we get the same result in both cases (but one being the transpose of the other). np.newaxis uses the slicing operator to recreate the array while np.reshape reshapes the array to the desired layout (assuming that the dimensions match; this is must for a reshape to happen).<jupyter_code>A = np.ones((3,4,5,6))
B = np.ones((4,6))
#A
(A + B[:, np.newaxis, :]).shape<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09125188536953242, 'fraction_numerical': 0.029411764705882353, 'mean_word_length': 5.4106280193236715, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '583114', 'license': 'MIT', 'n_tokens_mistral': 455, 'n_tokens_neox': 439, 'n_words': 182, 'path': 'Quantra/QuantIntroductionML/NewaxisEJ.ipynb', 'repo_name': 'IntroCursos/MachingLearning', 'size': '1326'}