你可以使用Python/NumPy如何将数值转换为数组?

huangapple go评论124阅读模式
英文:

How can I turn values into an array using Python/NumPy?

问题

以下是翻译好的部分:

这个练习的目标是使用NumPy将0-5范围内的值组织到一个数组中,这些值最初来自一个3x3的矩阵。

示例:

  1. [[1 1 3]
  2. [4 5 2]
  3. [3 0 0]]

这是我希望得到的输出:

  1. [2,2,1,2,1,1]

我尝试使用np.array()np.asarray(),但没有成功。此外,我考虑使用flatten()函数,但它不符合我的目标。

我的尝试:

  1. import numpy as np
  2. m = np.matrix([[1,1,3], [4,5,2], [3,0,0]]) # 用于获取值的原始矩阵
  3. print("原始矩阵:") # 打印原始矩阵
  4. print(m)
  5. print("出现次数:")
  6. for i in range(6):
  7. occur = (np.count_nonzero(m == i)) # 统计满足条件的元素数量
  8. print(i, ":", occur)

我的输出:

  1. 出现次数:
  2. 0 : 2
  3. 1 : 2
  4. 2 : 1
  5. 3 : 2
  6. 4 : 1
  7. 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 1 3]
  2. [4 5 2]
  3. [3 0 0]]

This is I wanted the output to come out:

  1. [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:

  1. import numpy as np
  2. m = np.matrix([[1,1,3], [4,5,2], [3,0,0]]) # Primary matrix, used for obtaining the values
  3. print("Original Matrix: ") # Print original matrix
  4. print(m)
  5. print("Occurrences: ")
  6. for i in range(6):
  7. occur = (np.count_nonzero(m == i)) # Count the number of elements satisfying the condition
  8. print(i, ":", occur)

My output:

  1. Occurrences:
  2. 0 : 2
  3. 1 : 2
  4. 2 : 1
  5. 3 : 2
  6. 4 : 1
  7. 5 : 1

答案1

得分: 1

我认为可以这样做:

  1. # 声明矩阵:
  2. mat = np.matrix([[1, 1, 3],
  3. [4, 5, 2],
  4. [3, 0, 0]])
  5. # 获取扁平化数组:
  6. arr = mat.getA1()
  7. # 获取二进制计数:
  8. bc = np.bincount(arr)

这样会得到相同的结果。

你可以使用Python/NumPy如何将数值转换为数组?

希望能对你有帮助!

英文:

I think it can be done this way:

  1. # declare matrix:
  2. mat = np.matrix([[1, 1, 3],
  3. [4, 5, 2],
  4. [3, 0, 0]])
  5. # get flattened array:
  6. arr = mat.getA1()
  7. # get the bincounts:
  8. bc = np.bincount(arr)

This would give you the same result

你可以使用Python/NumPy如何将数值转换为数组?

Hope this helps!

huangapple
  • 本文由 发表于 2023年6月6日 08:17:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76410705.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定