gpt4 book ai didi

python - 通过添加相应的值在 2D numpy 数组中创建唯一行

转载 作者:行者123 更新时间:2023-11-30 22:05:18 24 4
gpt4 key购买 nike

我在 python 中有一个二维 numpy 数组:

[[ 1  2  1  3  3]
[10 20 30 40 60]]

我希望在删除列之前第一行中具有唯一值在第二行中添加相应的值。因此,我的数组的输出将是这样的:

[[  1   2   3 ]
[ 40 20 100 ]]

我是 python 的新手,我想不出在更大范围内执行此操作的有效方法。

最佳答案

不幸的是,numpy没有内置的groupby函数(尽管有 ways to write them )。如果您愿意使用 pandas,这将很简单:

import pandas as pd

>>> pd.DataFrame(a.T).groupby(0,as_index=False).sum().values.T

array([[ 1, 2, 3],
[ 40, 20, 100]])

关于python - 通过添加相应的值在 2D numpy 数组中创建唯一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53067931/

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