多维 numpy 数组中的条件 groupby

Conditional groupby in multidimensional numpy array

我想按以下方式对数组进行分组:

a = np.array([ ['A', 1], ['man', 1], ['walks', 0], ['down', 0], ['the', 2], ['street', 2] ]) 
# would like the output to be:
b = np.array([ ['A man', 1], ['walks', 0], ['down', 0], ['the street', 2] ])

其中数组被分组为在一行或一列中具有相同项目的相邻项目,但仅适用于某些类型的条件而不适用于其他条件。

在我的例子中,我有一个 null 或零类型的条件,它应该被忽略,所有其他类型都发生分组。

我已经尝试了 itertools.groupby 的一些变体,但我还没有弄清楚如何单独保留零大小写。

我有一个愚蠢的答案。我很确定有人会想出一些惊人的答案。但希望这对你有所帮助。

def combine_adjacent(lst):
    new_lst = []
    for i in range(len(lst)-1):
        if lst[i][1] == lst[i+1][1] and lst[i][1] != '0' and lst[i][1] != None:
            new_lst.append([lst[i][0]+' '+lst[i+1][0], lst[i][1]])
        elif lst[i][1] == '0':
            new_lst.append(lst[i])
    return np.array(new_lst)

输入

a = np.array([ ['A', 1], ['man', 1], ['walks', 0], ['down', 0], ['the', 2], ['street', 2] ])
combine_adjacent(a)

输出

array([['A man', '1'],
   ['walks', '0'],
   ['down', '0'],
   ['the street', '2']], 
  dtype='<U10')

我认为 pandas 在这种情况下是一个不错的选择

import pandas as pd
import numpy as np

a = np.array([ ['A', 1], ['man', 1], ['walks', 0], ['down', 0], ['the', 2], ['street', 2], ]) 

# make np array into pandas dataframe
df = pd.DataFrame(a, columns=['word', 'group'])

# groupby the group column, ignoring the 0 group
word_groups = df[df['group'].astype(int) != 0].groupby('group', as_index=False)

# aggregate words in same group
joined_groups = word_groups.aggregate(lambda x: ' '.join(x))

# add the zero group back in
joined_groups.append(df[df['group'].astype(int) == 0])

如果你想从 pandas 数据帧返回一个 np 数组,只需使用 .values 属性