【发布时间】: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 -- 我会澄清