3 回答

TA贡献1860条经验 获得超8个赞
您也可以尝试以下答案。它不使用numpy,而是基于在sets中查找唯一元素的使用groupby。
table = [[15, 29, 6, 2],
[16, 9, 8, 0],
[7, 27, 16, 0]]
def averages(table, col, by):
columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary
'''groupby_unq: tuple data type
stores list of unique entries in groupby.'''
groupby_unq = tuple(set(groupby))
'''avg: numpy.ndarray data type
numpy array of zeros of same length as groupby_unq.'''
avg = np.zeros( len(groupby_unq) )
for i in range(len(groupby)):
for j in range(len(groupby_unq)):
if(groupby[i]==groupby_unq[j]): avg[j]+=columns[i]
avgdict = dict( (groupby_unq[i], avg[i]) for i in range(len(avg)) )
return avgdict
result = averages(table, 1, 3)
print result
{0: 36.0, 2: 29.0}

TA贡献1784条经验 获得超2个赞
我花了一分钟才弄清楚你想要完成什么,因为你的函数和变量名称引用了平均值,但你的输出是一个总和。
根据您的输出,您似乎正在尝试按另一列中的组聚合给定列中的行值。
这是推荐的解决方案(可能可以通过列表理解将其简化为单行)。这将循环遍历group by 中的唯一(使用set)值 ( b),agg_dict[b]通过正在处理为该组创建字典键 ( ),如果正在处理 group by,则对给定列 (col) 中的所有行求和 (table[i][by] == by。
table = [[15, 29, 6, 2],
[16, 9, 8, 0],
[7, 27, 16, 0]]
def aggregate(tbl, col, by):
agg_dict = {}
for b in list(set([table[i][by] for i in range(len(table))]))
agg_dict[b] = sum([table[i][col] for i in range(len(table)) if table[i][by] == b])
print(agg_dict)
aggregate(table, 1, 3)
添加回答
举报