基于索引的numpy重塑
numpy reshape based on index
我有一个数组:
arr = [
['00', '01', '02'],
['10', '11', '12'],
]
我想根据它的索引重塑这个数组:
reshaped = [
[0, 0, '00'],
[0, 1, '01'],
[0, 2, '02'],
[1, 0, '10'],
[1, 1, '11'],
[1, 2, '12'],
]
是否有 numpy
或 pandas
的方法来做到这一点?还是我必须做旧的 for
?
for x, arr_x in enumerate(arr):
for y, val in enumerate(arr_x):
print(x, y, val)
您可以使用 np.indices
获取索引,然后将所有内容拼接在一起...
arr = np.array(arr)
i, j = np.indices(arr.shape)
np.concatenate([i.reshape(-1, 1), j.reshape(-1, 1), arr.reshape(-1, 1)], axis=1)
我会使用 numpy.ndenumerate 来达到这个目的,方法如下:
import numpy as np
arr = np.array([['00', '01', '02'],['10', '11', '12']])
output = [[*inx,x] for inx,x in np.ndenumerate(arr)]
print(*output,sep='\n') # print sublists in separate lines to enhance readibility
输出:
[0, 0, '00']
[0, 1, '01']
[0, 2, '02']
[1, 0, '10']
[1, 1, '11']
[1, 2, '12']
作为旁注:这个动作是不是重塑,因为重塑意味着元素的移动,因为输出包含更多的单元格,所以不可能仅仅通过重塑来完成。
我有一个数组:
arr = [
['00', '01', '02'],
['10', '11', '12'],
]
我想根据它的索引重塑这个数组:
reshaped = [
[0, 0, '00'],
[0, 1, '01'],
[0, 2, '02'],
[1, 0, '10'],
[1, 1, '11'],
[1, 2, '12'],
]
是否有 numpy
或 pandas
的方法来做到这一点?还是我必须做旧的 for
?
for x, arr_x in enumerate(arr):
for y, val in enumerate(arr_x):
print(x, y, val)
您可以使用 np.indices
获取索引,然后将所有内容拼接在一起...
arr = np.array(arr)
i, j = np.indices(arr.shape)
np.concatenate([i.reshape(-1, 1), j.reshape(-1, 1), arr.reshape(-1, 1)], axis=1)
我会使用 numpy.ndenumerate 来达到这个目的,方法如下:
import numpy as np
arr = np.array([['00', '01', '02'],['10', '11', '12']])
output = [[*inx,x] for inx,x in np.ndenumerate(arr)]
print(*output,sep='\n') # print sublists in separate lines to enhance readibility
输出:
[0, 0, '00']
[0, 1, '01']
[0, 2, '02']
[1, 0, '10']
[1, 1, '11']
[1, 2, '12']
作为旁注:这个动作是不是重塑,因为重塑意味着元素的移动,因为输出包含更多的单元格,所以不可能仅仅通过重塑来完成。