gpt4 book ai didi

python - 更多 Pythonic/Pandaic 方法循环遍历 pandas 系列

转载 作者:太空狗 更新时间:2023-10-29 22:03:26 26 4
gpt4 key购买 nike

这很可能是非常基本的东西,但我无法弄清楚。假设我有一个这样的系列:

s1 = pd.Series([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4])

如何在不恢复使用 for 循环的情况下对该系列的子系列进行操作?

例如,假设我想将它变成一个包含四个元素的新系列。这个新系列中的第一个元素是原始系列中前三个元素 (1, 1, 1) 的总和,第二个元素是后三个元素 (2, 2, 2) 的总和,依此类推:

s2 = pd.Series([3, 6, 9, 12])

我该怎么做?

最佳答案

你也可以使用 np.add.reduceat通过指定每第 3 个元素要减少的切片并计算它们的运行总和:

>>> pd.Series(np.add.reduceat(s1.values, np.arange(0, s1.shape[0], 3)))
0 3
1 6
2 9
3 12
dtype: int64

时序约束:

arr = np.repeat(np.arange(10**5), 3)
s = pd.Series(arr)
s.shape
(300000,)

# @IanS soln
%timeit s.rolling(3).sum()[2::3]
100 loops, best of 3: 15.6 ms per loop

# @Divakar soln
%timeit pd.Series(np.bincount(np.arange(s.size)//3, s))
100 loops, best of 3: 5.44 ms per loop

# @Nikolas Rieble soln
%timeit pd.Series(np.sum(np.array(s).reshape(len(s)/3,3), axis = 1))
100 loops, best of 3: 2.17 ms per loop

# @Nikolas Rieble modified soln
%timeit pd.Series(np.sum(np.array(s).reshape(-1, 3), axis=1))
100 loops, best of 3: 2.15 ms per loop

# @Divakar modified soln
%timeit pd.Series(s.values.reshape(-1,3).sum(1))
1000 loops, best of 3: 1.62 ms per loop

# Proposed solution in post
%timeit pd.Series(np.add.reduceat(s.values, np.arange(0, s.shape[0], 3)))
1000 loops, best of 3: 1.45 ms per loop

关于python - 更多 Pythonic/Pandaic 方法循环遍历 pandas 系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41485471/

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