【问题标题】:split an array into a list of arrays将数组拆分为数组列表
【发布时间】:2018-11-14 18:42:51
【问题描述】:

如何通过分组变量拆分二维数组,并返回数组列表(顺序也很重要)。

为了显示预期的结果,R中的等价物可以做为

> (A = matrix(c("a", "b", "a", "c", "b", "d"), nr=3, byrow=TRUE)) # input
     [,1] [,2]
[1,] "a"  "b" 
[2,] "a"  "c" 
[3,] "b"  "d" 
> (split.data.frame(A, A[,1])) # output
$a
     [,1] [,2]
[1,] "a"  "b" 
[2,] "a"  "c" 

$b
     [,1] [,2]
[1,] "b"  "d" 

编辑:澄清一下:我想根据第一列中的唯一值将数组/矩阵A 拆分为多个数组的列表。也就是说,将A 拆分为一个数组,其中第一列有一个a,另一个数组的第一列有一个b

我试过 Python equivalent of R "split"-function 但这给出了三个数组

import numpy as np
import itertools
A = np.array([["a", "b"], ["a", "c"], ["b", "d"]])
b = a[:,0]

def split(x, f):
     return list(itertools.compress(x, f)), list(itertools.compress(x, (not i for i in f)))
split(A, b) 

([array(['a', 'b'], dtype='<U1'),
  array(['a', 'c'], dtype='<U1'),
  array(['b', 'd'], dtype='<U1')],
 [])

还有numpy.split,使用np.split(A, b),但需要整数。我虽然可以使用How to convert strings into integers in Python? 将字母转换为整数,但即使我传递整数,它也不会按预期拆分

c = np.transpose(np.array([1,1,2]))
np.split(A, c) # returns 4 arrays

这可以吗?谢谢

编辑:请注意,这是一个小例子,组的数量可能大于两个,并且可能没有排序。

【问题讨论】:

  • 不确定我是否理解您的预期输出@user2957945
  • 好的,谢谢@RafaelC -- 我会澄清

标签: python arrays numpy


【解决方案1】:

你可以使用熊猫:

import pandas as pd
import numpy as np

a = np.array([["a", "b"], ["a", "c"], ["b", "d"]])

listofdfs = {}
for n,g in pd.DataFrame(a).groupby(0):
    listofdfs[n] = g

listofdfs['a'].values

输出:

array([['a', 'b'],
       ['a', 'c']], dtype=object)

还有,

listofdfs['b'].values

输出:

array([['b', 'd']], dtype=object)

或者,您可以使用 itertools groupby:

import numpy as np
from itertools import groupby
l = [np.stack(list(g)) for k, g in groupby(a, lambda x: x[0])]

l[0]

输出:

array([['a', 'b'],
       ['a', 'c']], dtype='<U1')

还有,

l[1]

输出:

array([['b', 'd']], dtype='<U1')

【讨论】:

  • 太好了,谢谢 Scott,看起来不错。我曾考虑强制使用数据框,但我认为可能有数组工具——但这很好。
  • 太棒了,非常感谢。我正在浏览stackoverflow.com/questions/773/…,所以您的编辑为我提供了输出以供我理解
【解决方案2】:

如果我理解您的问题,您可以进行简单的切片,如下所示:

a = np.array([["a", "b"], ["a", "c"], ["b", "d"]])

x,y=a[:2,:],a[2,:]

x
array([['a', 'b'],
       ['a', 'c']], dtype='<U1')

y
array(['b', 'd'], dtype='<U1')

【讨论】:

  • 您好 G.Anderson,感谢您的回答。对于a = np.array([["a", "b"], ["b", "d"], ["a", "c"], ["b", "d"]]),或者如果有更多组,这将失败。道歉也许我的例子太少了。
  • 我明白了。在您编辑有关根据值对拆分进行分组之前,我已经回答了。也许this answer 可能会有所帮助?
  • 谢谢。这看起来很有希望——我只是想根据我的例子对其进行调整。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-30
  • 2015-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多