gpt4 book ai didi

python - 使用自己的内容将 numpy 数组扩展到特定范围

转载 作者:太空狗 更新时间:2023-10-30 02:58:08 25 4
gpt4 key购买 nike

将具有自己的值的数组扩展到特定大小的最有效方法是什么?

import numpy as np

# For this example, lets use an array with 4 items
data = np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]]) # 4 items

# I want to extend it to 10 items, here's the expected result would be:
data = np.array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[ 0, 1, 2],
[ 3, 4, 5]])

最佳答案

您可以连接数组:

def extend_array(arr, length):
factor, fraction = divmod(length, len(arr))
return np.concatenate([arr] * factor + [arr[:fraction]])

>>> extend_array(data, 10)

array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[ 0, 1, 2],
[ 3, 4, 5]])

关于python - 使用自己的内容将 numpy 数组扩展到特定范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35005855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com