从字母数字数组中提取python中的行

时间:2014-07-07 20:11:50

标签: python numpy

我在python中有这个数组,我想将以p结尾的行提取到一个新数组中。

array([[ 0,   6,   p],
       [ 1,   7,   m],
       [ 2,  10,   m],
       [ 3,   4,   p],
       [ 4,   1,   m],
       [ 5,  10,   p],
       [ 6,   6,   m],
       [ 7,   4,   m],
       [ 8,   6,   p],
       [ 9,   7,   p]])

3 个答案:

答案 0 :(得分:2)

简单的方法是使用numpy布尔索引,如下所示

a = numpy.array(a) # ensure its a numpy array
print a[a[:,-1]=="p"]

将其分解

mask = a[:,-1]=="p" #gives an array of True/False that is the same as the array, based on if last char is "p"
a[mask]  #indexes into the original array returning only the rows that end with "p"

答案 1 :(得分:1)

您可以使用过滤器来解决此问题。

data = [
    [ 0,   6,   "p"],
    [ 1,   7,   "m"],
    [ 2,  10,   "m"],
    [ 3,   4,   "p"],
    [ 4,   1,   "m"],
    [ 5,  10,   "p"],
    [ 6,   6,   "m"],
    [ 7,   4,   "m"],
    [ 8,   6,   "p"],
    [ 9,   7,   "p"]
]

new_data = filter(lambda l: l[2] == "p", data)

上面的结构假设您正在处理列表列表(数组数组),但是同样应该适用于元组和字典。

以下是对过滤功能的引用: https://docs.python.org/2/library/functions.html#filter

答案 2 :(得分:-1)

这在python中非常容易。

你可以这样做:

p = array[SOME_RANDOM_CELL];
print p[0]