【问题标题】:Conditional groupby in multidimensional numpy array多维numpy数组中的条件分组
【发布时间】:2017-12-02 05:05:54
【问题描述】:

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

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 的一些变体,因为我还没有弄清楚如何单独保留零大小写。

【问题讨论】:

  • 为什么不直接使用 filter 或添加一个将值转换为列表 ([v for k, v in it.groupby(*args) if len(v)) 的函数,这取决于您想要 lisp-ishness 还是惯用的 Python?

标签: python numpy group-by conditional


【解决方案1】:

我认为在这种情况下 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 属性

【讨论】:

  • 在某些情况下这将是一个很好的解决方案。我正在加载许多这样的数组,所以我不知道每次创建数据帧会导致多少开销。另外,我希望保留序列。
  • 我认为熊猫肯定有办法做到这一点,但也许这足以成为一个新问题?你是对的,这个解决方案并不理想,尽管它回答了原始问题
【解决方案2】:

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

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')

【讨论】:

  • 此解决方案适用于两列的情况,但如果有一种方法可以推广解决方案以在列数很大时跨元素连接,那就太好了。
  • 当然可以更好。我写的只是一个示例代码。您可以按照自己的方式对其进行优化。这就是编程的美妙之处。不是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 2021-03-26
相关资源
最近更新 更多