
本文旨在解决将一维 NumPy 数组重塑为尽可能接近正方形的二维数组的问题。由于并非所有数字都能完美分解为两个相等的整数,因此我们需要找到两个因子,它们的乘积等于数组的长度,并且尽可能接近。本文将提供几种实现此目的的方法,包括快速方法和更全面的方法,并提供代码示例。
在数据处理和科学计算中,经常需要将数据从一种形状转换为另一种形状。NumPy 提供了强大的 reshape 函数来实现这一点。然而,当需要将一维数组重塑为二维数组,并且希望二维数组的形状尽可能接近正方形时,问题就变得稍微复杂。例如,如果有一个长度为 500 的一维数组,我们希望将其重塑为一个形状接近 (22, 22) 的二维数组。
由于500无法开平方得到整数,无法直接重塑为正方形。因此,需要找到两个整数p和q,使得p*q=500,且p和q尽可能接近。
对于较小的 n 值,可以使用以下方法快速找到最接近的因子:
import numpy as np
from math import isqrt
def np_squarishrt(n):
"""
Finds two factors of n, p and q, such that p * q == n and p is as close as possible to sqrt(n).
"""
a = np.arange(1, isqrt(n) + 1, dtype=int) # Changed to include isqrt(n) itself
b = n // a
i = np.where(a * b == n)[0][-1]
return a[i], b[i]此函数首先生成一个从 1 到 sqrt(n) 的整数数组。然后,它计算 n 除以每个整数的结果。最后,它找到 a * b == n 的最后一个索引,并返回对应的 a 和 b 值。
示例:
a = np.arange(500) b = a.reshape(np_squarishrt(len(a))) print(b.shape) # 输出 (20, 25)
对于更大的 n 值,或者当需要更精确的控制时,可以使用以下方法:
from itertools import chain, combinations
from math import isqrt
import numpy as np
def factors(n):
"""
Generates the prime factors of n using the Sieve of Eratosthenes.
"""
while n > 1:
for i in range(2, int(n + 1)): # Changed n to int(n + 1) to avoid float errors
if n % i == 0:
n //= i
yield i
break
def uniq_powerset(iterable):
"""
Generates the unique combinations of elements from an iterable.
"""
s = list(iterable)
return chain.from_iterable(set(combinations(s, r)) for r in range(len(s)+1))
def squarishrt(n):
"""
Finds two factors of n, p and q, such that p * q == n and p is as close as possible to sqrt(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此方法首先使用 factors 函数找到 n 的所有质因数。然后,它使用 uniq_powerset 函数生成所有可能的质因数组合。最后,它遍历所有组合,找到两个因子 p 和 q,它们的乘积等于 n,并且 p 尽可能接近 sqrt(n)。
示例:
a = np.arange(500) b = a.reshape(squarishrt(len(a))) print(b.shape) # 输出 (20, 25)
通过以上方法,我们可以有效地将一维 NumPy 数组重塑为形状接近正方形的二维数组,从而方便后续的数据处理和分析。
以上就是将一维数组重塑为接近正方形的二维数组的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号