英文:
How can I turn values into an array using Python/NumPy?
问题
以下是翻译好的部分:
这个练习的目标是使用NumPy将0-5范围内的值组织到一个数组中,这些值最初来自一个3x3的矩阵。
示例:
[[1 1 3]
[4 5 2]
[3 0 0]]
这是我希望得到的输出:
[2,2,1,2,1,1]
我尝试使用np.array()
和np.asarray()
,但没有成功。此外,我考虑使用flatten()
函数,但它不符合我的目标。
我的尝试:
import numpy as np
m = np.matrix([[1,1,3], [4,5,2], [3,0,0]]) # 用于获取值的原始矩阵
print("原始矩阵:") # 打印原始矩阵
print(m)
print("出现次数:")
for i in range(6):
occur = (np.count_nonzero(m == i)) # 统计满足条件的元素数量
print(i, ":", occur)
我的输出:
出现次数:
0 : 2
1 : 2
2 : 1
3 : 2
4 : 1
5 : 1
英文:
The exercise consists in organizing values from 0-5 in an array, using NumPy, and those values were originally from a 3x3 matrix.
Example:
[[1 1 3]
[4 5 2]
[3 0 0]]
This is I wanted the output to come out:
[2,2,1,2,1,1]
I tried using np.array() and np.asarry(), but it didn't work. Moreover, I thought of using flatten() function, yet it didn't suit my goal.
What I tried:
import numpy as np
m = np.matrix([[1,1,3], [4,5,2], [3,0,0]]) # Primary matrix, used for obtaining the values
print("Original Matrix: ") # Print original matrix
print(m)
print("Occurrences: ")
for i in range(6):
occur = (np.count_nonzero(m == i)) # Count the number of elements satisfying the condition
print(i, ":", occur)
My output:
Occurrences:
0 : 2
1 : 2
2 : 1
3 : 2
4 : 1
5 : 1
答案1
得分: 1
我认为可以这样做:
# 声明矩阵:
mat = np.matrix([[1, 1, 3],
[4, 5, 2],
[3, 0, 0]])
# 获取扁平化数组:
arr = mat.getA1()
# 获取二进制计数:
bc = np.bincount(arr)
这样会得到相同的结果。
希望能对你有帮助!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论