重组数组数组并组合相同的项

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


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)

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


白猪掌柜的
浏览 152回答 1
1回答

慕斯709654

如果性能不是您最关心的问题,您可以将 Pandas 与Categorical Data和groupby. 这是有效的,因为默认情况下,groupby分类使用分类系列的笛卡尔积:import pandas as pd, numpy as np# construct dataframedf = pd.DataFrame(array, columns=['city', 'language', 'value'])# convert to categoriesfor col in ['city', 'language']:    df[col] = df[col].astype('category')# groupby.first or groupby.sum works if you have unique combinationsres = df.sort_values(['city', 'language'])\        .groupby(['city', 'language']).first().fillna(0).reset_index()print(res)    city language value0  City1  English     01  City1   French   1942  City1  Spanish   1633  City2  English  12394  City2   French   4565  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]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python