如何在numpy内连接两个数组?

时间:2013-07-29 14:31:39

标签: python arrays numpy

我有两个这样的数组:

A:

20131010 123 12321 12312312
20131011 123 12321 12312312
20131012 123 12321 12312312
20131013 123 12321 12312312

B:

20131010 bbbb sad sadsad
20131011 asd asdd asdad
20231012 123 12321 12312312
20141013 123 12321 12312312
20141023 123 12321 12312312

现在我需要在第一列(日期)内部连接这两个数组,结果应如下所示:

20131010 123 12321 12312312 bbbb sad sadsad
20131011 123 12321 12312312 asd asdd asdad

我该如何制作?请注意,每个列都有很多列,所以我不能命名每一列,但比较列确实只有一列。

2 个答案:

答案 0 :(得分:4)

这可记录在案,但请查看numpy.lib.recfunctions.join_by。它会做几种类似SQL的连接,包括内连接。我在numpy页面上看不到这个模块,但至少文档字符串会给你一些信息(从下面的1.9.1复制)。

请注意,这看起来需要一个结构化数组才能工作,因此您可能需要进行重组,而不是仅仅说"加入第0列"

Join arrays `r1` and `r2` on key `key`.

The key should be either a string or a sequence of string corresponding
to the fields used to join the array.  An exception is raised if the
`key` field cannot be found in the two input arrays.  Neither `r1` nor
`r2` should have any duplicates along `key`: the presence of duplicates
will make the output quite unreliable. Note that duplicates are not
looked for by the algorithm.

Parameters
----------
key : {string, sequence}
    A string or a sequence of strings corresponding to the fields used
    for comparison.
r1, r2 : arrays
    Structured arrays.
jointype : {'inner', 'outer', 'leftouter'}, optional
    If 'inner', returns the elements common to both r1 and r2.
    If 'outer', returns the common elements as well as the elements of
    r1 not in r2 and the elements of not in r2.
    If 'leftouter', returns the common elements and the elements of r1
    not in r2.
r1postfix : string, optional
    String appended to the names of the fields of r1 that are present
    in r2 but absent of the key.
r2postfix : string, optional
    String appended to the names of the fields of r2 that are present
    in r1 but absent of the key.
defaults : {dictionary}, optional
    Dictionary mapping field names to the corresponding default values.
usemask : {True, False}, optional
    Whether to return a MaskedArray (or MaskedRecords is
    `asrecarray==True`) or a ndarray.
asrecarray : {False, True}, optional
    Whether to return a recarray (or MaskedRecords if `usemask==True`)
    or just a flexible-type ndarray.

Notes
-----
* The output is sorted along the key.
* A temporary array is formed by dropping the fields not in the key for
  the two arrays and concatenating the result. This array is then
  sorted, and the common entries selected. The output is constructed by
  filling the fields with the selected entries. Matching is not
  preserved if there are some duplicates...

答案 1 :(得分:0)

你可以这样做:

C = np.hstack((A, B[:, 1:]))

假设AB具有相同的第一列,您只需将B中的所有内容添加到A,然后将第一列添加到{{1}}。