gpt4 book ai didi

python - 合并按列中的值分组的 2d numpy 数组

转载 作者:行者123 更新时间:2023-11-28 21:35:01 26 4
gpt4 key购买 nike

我有这个数组:

[['Burgundy Bichon Frise' '1' '137']
['Pumpkin Pomeranian' '1' '182']
['Purple Puffin' '1' '125']
['Wisteria Wombat' '1' '109']
['Burgundy Bichon Frise' '2' '168']
['Pumpkin Pomeranian' '2' '141']
['Purple Puffin' '2' '143']
['Wisteria Wombat' '2' '167']
['Burgundy Bichon Frise' '3' '154']
['Pumpkin Pomeranian' '3' '175']
['Purple Puffin' '3' '128']
['Wisteria Wombat' '3' '167']]

第一个索引包含动物的名称,第二个索引是它所在的区域,第三个索引是种群数量。我需要获取每个区域中物种的平均值,并获取每个区域中每个物种的最大值和最小值。因此,对于“Purple Puffins”,平均值应为 (125+143+128)/3 = 132

我对如何让 numpy 数组仅计算每个区域的人口感到非常困惑。

将这个二维数组分成多个二维数组会更好或更容易吗?

最佳答案

这看起来更像是 pandas 的任务,我们可以首先构建一个数据框:

import pandas as pd

df = pd.DataFrame([
['Burgundy Bichon Frise','1','137'],
['Pumpkin Pomeranian','1','182'],
['Purple Puffin','1','125'],
['Wisteria Wombat','1','109'],
['Burgundy Bichon Frise','2','168'],
['Pumpkin Pomeranian','2','141'],
['Purple Puffin','2','143'],
['Wisteria Wombat','2','167'],
['Burgundy Bichon Frise','3','154'],
['Pumpkin Pomeranian','3','175'],
['Purple Puffin','3','128'],
['Wisteria Wombat','3','167']], columns=['animal', 'region', 'n'])

接下来我们可以将regionn转换为数字,这将使统计数据更容易计算:

df.region = pd.to_numeric(df.region)
df.n = pd.to_numeric(df.n)

最后我们可以执行 .groupby(..) 然后计算聚合,例如:

>>> df[['animal', 'n']].groupby(('animal')).min()
n
animal
Burgundy Bichon Frise 137
Pumpkin Pomeranian 141
Purple Puffin 125
Wisteria Wombat 109
>>> df[['animal', 'n']].groupby(('animal')).max()
n
animal
Burgundy Bichon Frise 168
Pumpkin Pomeranian 182
Purple Puffin 143
Wisteria Wombat 167
>>> df[['animal', 'n']].groupby(('animal')).mean()
n
animal
Burgundy Bichon Frise 153.000000
Pumpkin Pomeranian 166.000000
Purple Puffin 132.000000
Wisteria Wombat 147.666667

编辑:获取每个动物的最小行数

我们可以使用idxmin/idxmax来获取每个动物的最小/最大行的索引号,然后使用 df.iloc[..] 获取这些行,例如:

>>> df.ix[df.groupby(('animal'))['n'].idxmin()]
animal region n
0 Burgundy Bichon Frise 1 137
5 Pumpkin Pomeranian 2 141
2 Purple Puffin 1 125
3 Wisteria Wombat 1 109
>>> df.ix[df.groupby(('animal'))['n'].idxmax()]
animal region n
4 Burgundy Bichon Frise 2 168
1 Pumpkin Pomeranian 1 182
6 Purple Puffin 2 143
7 Wisteria Wombat 2 167

此处 0, 5, 2, 3(对于 idxmin)是数据帧的“行号”。

关于python - 合并按列中的值分组的 2d numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52795120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com