You can multiply numpy arrays by scalars and it just works.
>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2, 4, 6],
[ 8, 10, 12]])
This is also a very fast and efficient operation. With your example:
>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
[6., 8.]])
Answer from iz_ on Stack OverflowYou can multiply numpy arrays by scalars and it just works.
>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2, 4, 6],
[ 8, 10, 12]])
This is also a very fast and efficient operation. With your example:
>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
[6., 8.]])
Using .multiply() (ufunc multiply)
a_1 = np.array([1.0, 2.0, 3.0])
a_2 = np.array([[1., 2.], [3., 4.]])
b = 2.0
np.multiply(a_1,b)
# array([2., 4., 6.])
np.multiply(a_2,b)
# array([[2., 4.],[6., 8.]])
Multiplying each integer in a list of lists by a float
Row multiplication in numpy array
How to multiply two arrays of matrices in Python?
List multiplication with a scalar
Videos
Hey guys! So I'm having trouble learning this exercise and I can't figure out why I keep getting this type error every time run this code. The task is to use a nested set of for loops to multiply each integer in a list of lists by a float
# These are all the numbers in the list
allscores = [['90', '83', '95'], ['100', '78', '89', '87', '90'], ['57', '82', '85', '89']]
# This is the nested set of for loops I used to multiply each number
for student_scores in allscores:
for i in range(len(student_scores)):
student_scores[i] = int(student_scores[i] * 1.05)
print("All scores after extra credit:", allscores)after running the code, pycharm responded with this
student_scores[i] = int(student_scores[i] * 1.05)
~~~~~~~~~~~~~~~~~~^~~~~~
TypeError: can't multiply sequence by non-int of type 'float'The list output should end up looking like this
All scores after extra credit: [[94, 87, 99], [105, 81, 93, 91, 94], [59, 86, 89, 93]]
Hello, help me please. I need to create an array with rows having subsequent values multiplied by the row number. For now I can just multiply all rows by one number. Something like print(arr[row * range(1, 5)]) doesn't work. How could I do row multiplication with a range of numbers?
arr = np.array([[i for i in range(5)],]*5)
print(arr)
for row in range(len(arr)):
print(arr[row]*5)