I have data in the following format:
JavaScript
x
5
1
[('user_1', 2, 1.0),
2
('user_2', 6, 2.5),
3
('user_3', 9, 3.0),
4
('user_4', 1, 3.0)]
5
And I want use this information to create a NumPy array that has the value 1.0 in position 2, value 2.5 in position 6, etc. All positions not listed in the above should be zeroes. Like this:
JavaScript
1
2
1
array([0, 3.0, 0, 0, 0, 0, 2.5, 0, 0, 3.0])
2
Advertisement
Answer
First reformat the data:
JavaScript
1
9
1
data = [
2
("user_1", 2, 1.0),
3
("user_2", 6, 2.5),
4
("user_3", 9, 3.0),
5
("user_4", 1, 3.0),
6
]
7
8
usernames, indices, values = zip(*data)
9
And then create the array:
JavaScript
1
7
1
length = max(indices) + 1
2
3
arr = np.zeros(shape=(length,))
4
arr[list(indices)] = values
5
6
print(arr) # array([0. , 3. , 1. , 0. , 0. , 0. , 2.5, 0. , 0. , 3. ])
7
Note that you need to convert indices to a list, otherwise when using it for indexing numpy will think it is trying to index multiple dimensions.