【问题标题】:Restructure an array of arrays and combine same terms重构数组数组并组合相同的项
【发布时间】:2018-12-10 08:06:50
【问题描述】:

我正在尝试编写一个函数,该函数接受一个数组数组,并在某些条件下将其重组为不同的形式。比如说:

array = [
    ["City1","Spanish", "163"],
    ["City1", "French", "194"],
    ["City2","English", "1239"],
    ["City2","Spanish", "1389"],
    ["City2", "French", "456"]
]

所以我想创建一个按城市字母顺序排序的新数组,以及按语言排序的列(按列排序可选),任何空值都将被 0 替换。例如,上述数组的输出应该是:

[
[0, 163, 194],
[1239, 1389, 456]
]

我写了这个方法,但我不确定它在逻辑上是否有意义。它绝对是硬编码的,我正在努力使它可以用于上述格式的任何输入。

import numpy as np

new_array = [[]]
x = 'City1'
y = 'City2'

def solution(arr):
    for row in arr:
        if row[0]==x:
            new_array[-1].append(row[2])
        else:
            x = x + 1
            c.append([row[2]])
solution(array)

我知道我需要修正语法,还需要编写一个循环来按字母顺序排序。对此的任何帮助将不胜感激,我想了解如何遍历这样的数组并执行不同的功能并将数组重组为新格式。

【问题讨论】:

  • 如我所见,您有一个列表,在您的情况下,我猜是关于城市的数据?我建议使用不可变数据类型来存储数据,例如元组(或命名元组)。无论如何,为了处理您的问题,我强烈建议使用内置函数。这样你就不需要循环,做一些魔术。您可以使用的一些功能是:groupby、sorted、map 等。一旦您正确地构建了数据,就很容易处理它。恐怕在你的情况下数据是一团糟..

标签: python arrays python-3.x numpy sorting


【解决方案1】:

如果性能不是您最关心的问题,您可以将 Pandas 与 Categorical Datagroupby 一起使用。这是因为默认情况下,groupby with categoricals 使用分类系列的笛卡尔积:

import pandas as pd, numpy as np

# construct dataframe
df = pd.DataFrame(array, columns=['city', 'language', 'value'])

# convert to categories
for col in ['city', 'language']:
    df[col] = df[col].astype('category')

# groupby.first or groupby.sum works if you have unique combinations
res = df.sort_values(['city', 'language'])\
        .groupby(['city', 'language']).first().fillna(0).reset_index()

print(res)

    city language value
0  City1  English     0
1  City1   French   194
2  City1  Spanish   163
3  City2  English  1239
4  City2   French   456
5  City2  Spanish  1389

然后,对于您想要的列表输出列表:

res_lst = res.groupby('city')['value'].apply(list).tolist()
res_lst = [list(map(int, x)) for x in res_lst]

print(res_lst)

[[0, 194, 163], [1239, 456, 1389]]

【讨论】:

  • 嗨,谢谢。我其实很关心记忆。我知道如何使用 pandas 数据帧来做到这一点,但我想将其保留为一个数组并在该级别进行重组,从数组到数组。如果您对此有任何意见,我将不胜感激!
  • @codingtherapy,实际上,分类数据通过分解字符串减少内存消耗(它只为每个字符串保存一个条目,并使用数字数据链接到您的数据框)。你必须用 NumPy 做一些类似的事情来尝试打败它,有点棘手。
  • 有趣,我原以为 pandas 本身会比 numpy 使用更多的内存,感谢您的洞察力!
猜你喜欢
  • 2018-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-18
相关资源
最近更新 更多