熊猫 Numpy 添加一列

2024-04-20 09:02:59 发布

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

我有一个形状为(n,)的numpy数组,它是一个包含多个元素的元组数组。有没有一种方法可以让我快速地将列添加到其中一个元组中&它仍然具有相同的形状(n,)?你知道吗


Tags: 方法numpy元素数组元组形状
2条回答

我想我找到了一个解决方案,它涉及到向结构数组中添加列:

 from numpy.lib import recfunctions
 a = recfunctions.append_fields(old_data,'new_column', 
                                new_array,dtypes=np.float64,
                                usemask=False)

由于这个问题没有答案,我写了一个可能有用的片段。可以使用np.zerosnp.hstack向数组中添加新列。你知道吗

import numpy as np

def main():
    my_tuples = np.array(((1,-2,3),(4,5,6))) 
    element = (7,8) #suppose you want to add this to my_tuples column

    #Solution 1
    print('shape before adding column', my_tuples.shape)
    new_tuples = np.zeros((my_tuples.shape[0],my_tuples.shape[1]+1));
    new_tuples[:,:-1] = my_tuples
    new_tuples[:,-1] = element
    print('column to be added ', element)
    print('shape after adding column using np.zeros', new_tuples.shape)
    print(new_tuples)

    #Solution 2
    new_tuples = np.hstack((my_tuples,np.zeros((my_tuples.shape[0],1))))
    new_tuples[:,-1] = element
    print('shape after adding column using np.hstack', new_tuples.shape)
    print(new_tuples)


if __name__ == '__main__':
    main()

输出:

shape before adding column (2, 3)
column to be added  (7, 8)
shape after adding column using np.zeros (2, 4)
[[ 1. -2.  3.  7.]
 [ 4.  5.  6.  8.]]
shape after adding column using np.hstack (2, 4)
[[ 1. -2.  3.  7.]
 [ 4.  5.  6.  8.]]

相关问题 更多 >