Python:求重复索引累加和的有效方法(numpy方法)
Python: effective way to find the cumulative sum of repeated index (numpy method)
我有一个二维 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
col0
并为 col1
找到 .sum()
。
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
我认为 pandas
方法(例如 @HarvIpan 提供的方法)最适合可读性和功能性,但由于您也要求使用 numpy
方法,这里有一种方法可以做到它在 numpy
中使用列表理解,这比你原来的循环更简洁:
np.array([[i,np.sum(bb[np.where(aa==i)])] for i in np.unique(aa)])
哪个returns:
array([[ 4. , 0.8],
[ 7. , 0.4],
[ 8. , 1.2],
[ 11. , 1.5],
[ 15. , 0.1],
[ 19. , 0.5]])
我有一个二维 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
col0
并为 col1
找到 .sum()
。
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
我认为 pandas
方法(例如 @HarvIpan 提供的方法)最适合可读性和功能性,但由于您也要求使用 numpy
方法,这里有一种方法可以做到它在 numpy
中使用列表理解,这比你原来的循环更简洁:
np.array([[i,np.sum(bb[np.where(aa==i)])] for i in np.unique(aa)])
哪个returns:
array([[ 4. , 0.8],
[ 7. , 0.4],
[ 8. , 1.2],
[ 11. , 1.5],
[ 15. , 0.1],
[ 19. , 0.5]])