
本文旨在解决将一维 NumPy 数组重塑为尽可能接近正方形的二维矩阵的问题。由于并非所有数字都能完美分解为两个相等的整数,因此我们需要找到两个因子,它们的乘积等于数组的长度,并且这两个因子尽可能接近。本文将介绍两种实现此目标的 Python 代码方法,并提供代码示例和使用注意事项,帮助读者理解和应用这些方法。
在数据处理和科学计算中,经常需要将数据重塑为不同的形状以适应特定的算法或分析需求。当需要将一维 NumPy 数组转换为二维矩阵时,如果目标是创建一个尽可能接近正方形的矩阵,就需要找到两个因子,它们的乘积等于数组的长度,并且这两个因子尽可能接近。
以下介绍两种方法来实现这个目标。
这种方法适用于相对较小的 n 值,它通过遍历小于等于 n 平方根的整数,找到 n 的因子。
import numpy as np
from math import isqrt
def np_squarishrt(n):
a = np.arange(1, isqrt(n) + 1, dtype=int)
b = n // a
i = np.where(a * b == n)[0][-1]
return a[i], b[i]
# 示例
a = np.arange(500)
rows, cols = np_squarishrt(len(a))
b = a.reshape((rows, cols))
print(b.shape) # 输出 (20, 25)代码解释:
注意事项:
这种方法使用因式分解和幂集组合来找到最接近的因子。
import numpy as np
from itertools import chain, combinations
from math import isqrt
def factors(n):
while n > 1:
for i in range(2, n + 1):
if n % i == 0:
n //= i
yield i
break
def uniq_powerset(iterable):
"""
Similar to powerset(it) but without repeats.
uniq_powerset([1,1,2]) --> (), (1,), (2,), (1, 1), (1, 2), (1, 1, 2)
"""
s = list(iterable)
return chain.from_iterable(set(combinations(s, r)) for r in range(len(s)+1))
def squarishrt(n):
p = isqrt(n)
if p**2 == n:
return p, p
bestp = 1
f = list(factors(n))
for t in uniq_powerset(f):
if 2 * len(t) > len(f):
break
p = np.prod(t) if t else 1
q = n // p
if p > q:
p, q = q, p
if p > bestp:
bestp = p
return bestp, n // bestp
# 示例
a = np.arange(500)
b = a.reshape(squarishrt(len(a)))
print(b.shape)代码解释:
注意事项:
本文介绍了两种将一维 NumPy 数组重塑为接近正方形的二维矩阵的方法。第一种方法适用于相对较小的 n 值,而第二种方法更通用,但计算成本更高。选择哪种方法取决于具体的需求和性能考虑。在实际应用中,可以根据数组的大小和所需的精度来选择最合适的方法。
以上就是将一维 NumPy 数组重塑为接近正方形的矩阵的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号