【问题标题】:Python: effective way to find the cumulative sum of repeated index (numpy method) [duplicate]Python:查找重复索引的累积和的有效方法(numpy方法)[重复]
【发布时间】:2018-11-17 17:01:07
【问题描述】:

我有一个 2d numpy 数组,第一列中有重复值。 第二列中重复的值可以有任何对应的值。

使用 numpy 很容易找到 cumsum,但是,我必须找到所有重复值的 cumsum。

我们如何使用 numpy 或 pandas 有效地做到这一点?

在这里,我使用无效的for循环解决了这个问题。 我想知道是否有更优雅的解决方案。

问题 我们如何才能以更有效的方式获得相同的结果?

我们将不胜感激。

#!python
# -*- coding: utf-8 -*-#
#
# Imports
import pandas as pd
import numpy as np
np.random.seed(42)  # make results reproducible

aa = np.random.randint(1, 20, size=10).astype(float)
bb = np.arange(10)*0.1

unq = np.unique(aa)

ans = np.zeros(len(unq))
print(aa)
print(bb)
print(unq)

for i, u in enumerate(unq):
    for j, a in enumerate(aa):
        if a == u:
            print(a, u)
            ans[i] += bb[j]

print(ans)


"""
# given data
idx  col0  col1
0    7.    0.0 
1    15.   0.1
2    11.   0.2
3    8.    0.3
4    7.    0.4
5    19.   0.5
6    11.   0.6
7    11.   0.7
8    4.    0.8
9    8.    0.9


# sorted data
4.    0.8
7.    0.0
7.    0.4
8.    0.9
8.    0.3
11.   0.6
11.   0.7
11.   0.2
15.   0.1
19.   0.5

# cumulative sum for repeated serial
4.    0.8
7.    0.0 + 0.4
8.    0.9 + 0.3
11.   0.6 + 0.7 + 0.2
15.   0.1
19.   0.5

# Required answer
4.    0.8 
7.    0.4    
8.    1.2
11.   1.5
15.   0.1
19.   0.5
"""

【问题讨论】:

  • 我认为您正在寻找groupby()...
  • 如果 aa 是整数,并且从不太大的间隔开始,您可以使用 np.bincount(aa, bb, aa.max()+1) 我没有对它进行基准测试,但希望它通常比熊猫更好地扩展。

标签: python pandas numpy data-manipulation numpy-ndarray


【解决方案1】:

您可以groupby col0 并找到.sum()col1

df.groupby('col0')['col1'].sum()

输出:

col0
4.0     0.8
7.0     0.4
8.0     1.2
11.0    1.5
15.0    0.1
19.0    0.5
Name: col1, dtype: float64

【讨论】:

  • 非常感谢,我们也可以在 numpy 中做吗?
  • @astro123, this 问题谈论 numpy 方法。
【解决方案2】:

我认为 @HarvIpan 提供的 pandas 方法最适合可读性和功能性,但由于您也要求使用 numpy 方法,因此这是在 numpy 中使用的一种方法一个列表理解,比你原来的循环更简洁:

np.array([[i,np.sum(bb[np.where(aa==i)])] for i in np.unique(aa)])

返回:

array([[  4. ,   0.8],
       [  7. ,   0.4],
       [  8. ,   1.2],
       [ 11. ,   1.5],
       [ 15. ,   0.1],
       [ 19. ,   0.5]])

【讨论】:

    猜你喜欢
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 2021-08-31
    • 2019-06-24
    • 2020-11-18
    相关资源
    最近更新 更多