将新记录添加到numpy结构化数组中

时间:2013-07-02 10:55:09

标签: python arrays numpy adjacency-matrix recarray

这是早期学习numpy数组的延续 结构化数组是从列表的元素创建的 - 然后填充值(下面未显示)。

>>> o = ['x','y','z']
>>> import numpy as np
>>> b = np.zeros((len(o),), dtype=[(i,object) for i in o])
>>> b
array([(0, 0, 0, 0, 0), (0, 0, 0, 0, 0), (0, 0, 0, 0, 0)], 
      dtype=[('x', '|O4'), ('y', '|O4'), ('z', '|O4')])

填充的数组如下所示:

    x   y   z   
x   0   1   0   
y   1   0   1,5 
z   0   1,5 0   

1.我们如何在上面添加新顶点?
2.一旦添加了顶点,将以下数组添加到结构化数组的最干净的过程是什么(注意:并非此数组中的所有顶点都是新的):

    d    e      y
d   0   '1,2'   0
e  '1,2' 0     '1'
f   0   '1'     0

预期产量(请耐心等待):

    x   y   z   d   e   f
x   0   1   0   0   0   0
y   1   0   1,5 0   1   0
z   0   1,5 0   0   0   0
d   0   0   0   0   1,2 0
e   0   1   0   1,2 0   0
f   0   0   0   0   1   0

1 个答案:

答案 0 :(得分:0)

好像是python pandas的工作。

>>> import numpy as np
>>> import pandas as pd
>>> data=np.zeros((4,5))
>>> df=pd.DataFrame(data,columns=['x','y','z','a','b'])
>>> df
   x  y  z  a  b
0  0  0  0  0  0
1  0  0  0  0  0
2  0  0  0  0  0
3  0  0  0  0  0
>>> df['c']=0  #Add a new column
>>> df
   x  y  z  a  b  c
0  0  0  0  0  0  0
1  0  0  0  0  0  0
2  0  0  0  0  0  0
3  0  0  0  0  0  0

>>> new_data=pd.DataFrame([['0','1,2','0'],['1,2','0','1'],['0','1','0']],columns=['d','e','y'])
>>> new_data
     d    e  y
0    0  1,2  0
1  1,2    0  1
2    0    1  0

>>> df.merge(new_data,how='outer') #Merge data
    x  y   z   a   b   c    d    e
0   0  0   0   0   0   0  NaN  NaN
1   0  0   0   0   0   0  NaN  NaN
2   0  0   0   0   0   0  NaN  NaN
3   0  0   0   0   0   0  NaN  NaN
4 NaN  0 NaN NaN NaN NaN    0  1,2
5 NaN  0 NaN NaN NaN NaN    0    1
6 NaN  1 NaN NaN NaN NaN  1,2    0

有很多方法可以合并您展示的数据,您能否详细解释一下您希望结束数组看起来像什么?