[英]Repeat values in 1D array across multiple dimensions
I have a 1 dimensional array of CO2 values where I need to repeat each value over lon/lat dimensions [360, 720] creating an array of dims [365, 360, 720] - ie 1 year of daily CO2 values across longitude and latitude.我有一个一维 CO2 值数组,我需要在 lon/lat 维度 [360, 720] 上重复每个值,创建一个数组 [365, 360, 720] - 即 1 年跨经度和纬度的每日 CO2 值.
I would want to take an array:我想要一个数组:
a = np.array([343.79258065, 343.79096774, 343.78935484])
And tile the first value across an array of dims [360, 720], then tile the second value across the same dims [360, 720], and do that for n values in the array (365 times in my case)然后将第一个值平铺在一组昏暗 [360, 720] 上,然后将第二个值平铺在相同的昏暗 [360, 720] 上,并对数组中的 n 个值执行此操作(在我的情况下为 365 次)
A small dim example of this would be (but please note the dims I want below):一个小的暗淡例子是(但请注意下面我想要的暗淡):
array([[343.79258065, 343.79258065, 343.79258065, ...],
[343.79096774, 343.79096774, 343.79096774, ...],
[343.78935484, 343.78935484, 343.78935484, ...]])
So effectively each value in array a
would be repeated (tiled?) over an array of dims [360, 720] for 365 layers resulting in a 3D array of dims [365, 360, 720].如此有效地,数组a
每个值都将在 365 层的暗淡数组 [360, 720] 上重复(平铺?),从而产生暗淡 [365, 360, 720] 的 3D 数组。
It would be great to solve this with broadcast_to()
if it's possible.如果可能的话,用broadcast_to()
解决这个问题会很棒。 Some links that don't quite do what I want: Repeating values n times and Repeat across multiple dimensions一些不太符合我的要求的链接: 重复值 n 次并在多个维度上重复
I hope I understand your question correctly!我希望我能正确理解你的问题! I would do this by first reshaping the array into (N,1,1)
, then expanding each of those 1x1 sub-arrays into the repeated arrays you wanted to be (360, 720) using numpy's np.repeat function.我会首先将数组重塑为(N,1,1)
,然后使用 numpy 的np.repeat函数将每个 1x1 子数组扩展为您想要的重复数组 (360, 720)。 Here's how I did it:这是我如何做到的:
a = np.array([343.79258065, 343.79096774, 343.78935484]).reshape(-1,1,1)
a = np.repeat(a, 360, axis=1)
a = np.repeat(a, 720, axis=2)
print(a.shape)
>> (3, 360, 720)
If this isn't what you had in mind, please let me know!如果这不是您的想法,请告诉我! Each of the N
360x720 arrays contains only repeated instances of the i
th value of the initial array ( a[i]
), by the way.顺便说一下, N
360x720 数组中的每一个只包含初始数组 ( a[i]
) 的第i
个值的重复实例。
I'm adding a broadcast_to()
answer that a user bizarrely responded with then deleted, because I did ask whether it was possible in the original question.我添加了一个broadcast_to()
答案,用户奇怪地回复了这个答案,然后删除了,因为我确实问过在原始问题中是否可行。 Thanks to both @dsillman2000 and the phantom user.感谢@dsillman2000 和幻影用户。
np.broadcast_to(a.reshape(-1,1,1), (len(a),360,720))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.