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

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

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)

这样会得到相同的结果。

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

希望能对你有帮助!

英文:

I think it can be done this way:

# declare matrix:
mat = np.matrix([[1, 1, 3], 
 [4, 5, 2],
 [3, 0, 0]])

# get flattened array:
arr = mat.getA1()

# get the bincounts:
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:

确定