繁体   English   中英

将两个不同数据类型的1D阵列组合成PYTHON中的1个2D阵列

[英]Combining two 1D arrays of different data types into 1 2D array in PYTHON

我有2个数字列表:a和b。 A是类型为integer的节点号列表,b是类型为float64的X坐标列表。 我想将这两个等长数组(N)组合成一个保留数据类型的Nx2数组。 我稍后在一些布尔测试中使用这个数组,所以我需要第一列是整数。 我一直在用:

nodeID = np.concatenate([[a],[b]]).T

但显然这会将所有内容转换为浮点数。

谢谢!

实现目标的一种方法是使用numpydtypehttp://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html中所述。

>>> import numpy as np
>>> dt = np.dtype([('a', np.int64, 1), ('b', np.float64, 1)])
>>> a = np.array([1,2,3,4], dtype=np.int64)
>>> b = np.array([1.,2.,3.,4.], dtype=np.float64)
>>> ab = np.array(zip(a,b), dtype=dt)
>>> ab[:]['a']
array([1, 2, 3, 4])
>>> ab[:]['b']
array([ 1.,  2.,  3.,  4.])

你可以在这里使用zip()。 如果你只是比较列表a的元素,那么这里的问题是什么?

a =[1,2,3,4]
b =["Hello", "world", "fellow"]

x=zip(a,b)
print x

for a,b in x:
  if a == someThing:
     doSomething()

我假设是因为你在标题中提到了一个2D列表,你想要一个如下所示的列表,其中每个节点和coord都保留了它们的类型:

[[node1, coord1], [node2, coord2], ... ]

您可以在没有任何模块的三个快速行中执行此操作,保留每个变量的类型:

nodeID = []
for i, node in enumerate(a):
    nodeID.append([node, b[i]])

因此,您将拥有一个2D列表。 2D列表中的每个元素本身都是包含一对节点和坐标的另一个列表。 由于Python对类型不敏感,因此将保留节点和坐标的类型。 您将访问每对:

pair1 = nodeID[0]
pair2 = nodeID[1]
pairx = nodeID[x]

他们的内容包括:

node1 = nodeID[0[0]]
node2 = nodeID[1[0]]
coord1 = nodeID[0[1]]
coord2 = nodeID[1[1]]

希望这会有所帮助。 :-)

zip功能是最简单的方式。 简短的例子:

>>> a = [1, 2, 3, 4, 5]
>>> b = [1.1, 2.2, 3.3, 4.4, 5.5]
>>> zip(a,b)
[(1, 1.1), (2, 2.2), (3, 3.3), (4, 4.4), (5, 5.5)]
>>> 

如果你想从zip(a,b)获得a ,只需写:

>>> [x[0] for x in zip(a, b)]
[1, 2, 3, 4, 5]

一个好主意是从两个列表中创建字典:

>>> keys = [1,2,3,4,5]
>>> values = [1.1,2.2,3.3,4.4,5.5]
>>> dictionary = dict(zip(keys, values))
>>> dictionary
{1: 1.1, 2: 2.2, 3: 3.3, 4: 4.4, 5: 5.5}

但要小心,字典中的顺序不会保存。 从字典访问数据非常简单:

>>> dictionary.keys()
[1, 2, 3, 4, 5]
>>> dictionary.values()
[1.1, 2.2, 3.3, 4.4, 5.5]
>>> dictionary[1]
1.1
>>> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM