展平numpy数组并保留索引值

2024-06-16 14:42:46 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下矩阵pandasnumpy

A = np.array([[1,2,3],[4,5,6],[7,8,9]])

>>> array([[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]])

我正在寻找一种方法,将此数组重塑为1D,并将该单元格的索引保留为列名,这样,如果要展平上述内容,结果将如下所示:

>>> array([['i1j1', 'i1j2', 'i1j3', 'i2j1', 'i2j2', 'i2j3', 'i3j1', 'i3j2','i3j3'],
          ['1', '2', '3', '4', '5', '6', '7', '8', '9']], dtype='<U4')

非常感谢


Tags: 方法numpy内容pandasnp矩阵数组array
3条回答

还有一种方法:

b = (pd.DataFrame(A)
     .rename(lambda x: 'i{}'.format(x+1))
     .rename(lambda x: 'j{}'.format(x+1),axis=1)
     .stack())
b = b.set_axis(b.index.map(''.join)).to_frame().T

尝试:

df = pd.DataFrame(A, 
                  columns=[f'j{j+1}' for j in range(A.shape[1])], 
                  index=[f'i{i+1}' for i in range(A.shape[0])]).stack()
df.index = [f'{i}{j}' for i, j in df.index]
df_out = df.to_frame().T
df_out

输出:

   i1j1  i1j2  i1j3  i2j1  i2j2  i2j3  i3j1  i3j2  i3j3
0     1     2     3     4     5     6     7     8     9

正如您所注意到的,有一种非常直观的方法来计算展平阵列的索引。我们可以使用np.meshgrid来利用这一点

xv, yv = np.meshgrid(np.arange(A.shape[0]), np.arange(A.shape[1])) 
indices = np.stack(( yv.flatten(), xv.flatten()), axis=1)

输出

array([[0, 0],
       [0, 1],
       [0, 2],
       [1, 0],
       [1, 1],
       [1, 2],
       [2, 0],
       [2, 1],
       [2, 2]])

编辑:

要获得示例中的确切格式,请尝试:

xv, yv = np.meshgrid(np.arange(A.shape[0]) + 1, np.arange(A.shape[1]) + 1)  
rows = np.char.add('i', yv.flatten().astype(str)) 
cols = np.char.add('j', xv.flatten().astype(str))
indicies = np.char.add(rows,cols)
np.stack((indicies, A.flatten()))

返回

array([['i1j1', 'i1j2', 'i1j3', 'i2j1', 'i2j2', 'i2j3', 'i3j1', 'i3j2', 'i3j3'],
       ['1', '2', '3', '4', '5', '6', '7', '8', '9']], dtype='<U24')

相关问题 更多 >