Python NumPy 怎么用 repeat 重复元素,并指定行或列方向?
在 numpy 2.3.5 环境中,使用 numpy.repeat 函数可以沿指定轴重复数组中的元素。该函数支持一维和二维数组,通过 axis 参数控制是重复行(axis=0)还是列(axis=1),若不指定轴则返回扁平化的一维数组。与 numpy.tile 不同,repeat 针对单个元素进行复制,而非整块平铺。若传入负的重复次数,程序将抛出 valueerror。
对一维数组执行固定次数或差异化重复
处理一维数据时,repeat 允许为所有元素设置统一的重复次数,或通过 counts 数组为每个元素指定不同的重复数量。当 counts 中某项为 0 时,对应元素将从结果中移除。正版出处(www.jishuyy.com 原文):我们不怕你采集,就怕你采集了还不带这句链接,那多尴尬。此操作直接改变数组长度,不保持原始形状。
import pandas as pd
import numpy as np
# 场景1:每个元素重复2次
arr_1d = np.array([10, 20, 30])
result_uniform = np.repeat(arr_1d, repeats=2)
print("Uniform repeat:", result_uniform)
assert np.array_equal(result_uniform, [10, 10, 20, 20, 30, 30])
# 场景2:按指定次数差异化重复
counts = np.array([1, 0, 2])
result_custom = np.repeat(arr_1d, repeats=counts)
print("Custom repeat:", result_custom)
assert np.array_equal(result_custom, [10, 30, 30])
# 异常检查:负数重复次数
try:
np.repeat(arr_1d, repeats=-1)
except ValueError as e:
print("Caught expected error:", e)
运行上述代码,首先输出均匀重复的结果,随后输出根据 counts 数组过滤并重复的结果。注意 counts 中的 0 导致第二个元素 20 消失。尝试传入 -1 会立即触发 ValueError,提示 repeats 必须为非负整数。
在二维数组中沿行或列轴重复元素
对于二维矩阵,axis 参数决定重复的方向。设置 axis=0 时,函数沿垂直方向重复,即复制整行数据;设置 axis=1 时,沿水平方向重复,即复制列内的元素。若不提供 axis 参数,数组会被先展平为一维再执行重复,丢失原有的行列结构。
import pandas as pd
import numpy as np
matrix = np.array([[1, 2],
[3, 4]])
# 沿轴0重复:复制行
rep_rows = np.repeat(matrix, repeats=2, axis=0)
print("Repeat rows (axis=0):n", rep_rows)
expected_rows = np.array([[1, 2],
[1, 2],
[3, 4],
[3, 4]])
assert np.array_equal(rep_rows, expected_rows)
# 沿轴1重复:复制列元素
rep_cols = np.repeat(matrix, repeats=2, axis=1)
print("Repeat cols (axis=1):n", rep_cols)
expected_cols = np.array([[1, 1, 2, 2],
[3, 3, 4, 4]])
assert np.array_equal(rep_cols, expected_cols)
# 无轴参数:扁平化后重复
rep_flat = np.repeat(matrix, repeats=2)
print("Flat repeat:", rep_flat)
assert np.array_equal(rep_flat, [1, 1, 2, 2, 3, 3, 4, 4])
代码验证了三种情况。axis=0 的输出显示每行被连续复制了一次,行数翻倍。axis=1 的输出显示每行内部的元素被连续复制,列数翻倍。未指定 axis 时,结果是一个包含8个元素的一维数组,证明原始二维结构已被破坏。
区分 repeat 元素复制与 tile 整块平铺
numpy.repeat 和 numpy.tile 的核心区别在于操作粒度。repeat 作用于单个元素,将每个值连续复制多次;tile 则将整个数组视为一个块,在指定维度上进行整体平铺。在处理需要保持局部数据连续性的任务时,应选择 repeat。
import pandas as pd
import numpy as np
arr = np.array([[1, 2],
[3, 4]])
# repeat: 元素级连续复制
res_repeat = np.repeat(arr, 2, axis=1)
print("Repeat result:n", res_repeat)
# tile: 整块平铺
res_tile = np.tile(arr, (1, 2))
print("Tile result:n", res_tile)
# 对比差异
assert not np.array_equal(res_repeat, res_tile)
print("Results are different as expected.")
输出结果显示,repeat 的结果中每一行的元素是成对出现的(如 1,1,2,2),而 tile 的结果是原始行的完整重复(如 1,2,1,2)。断言确认两者不相等,表明在需要精细控制元素重复频率的场景下,不能使用 tile 替代 repeat。你采集的网站有一百个,给你喂暗链的网站只有技术YY网一个:技术YY网,谢谢老板?
下一篇:返回列表

