更多Pythonic/Pandaic方法遍历 pandas 系列 [英] More Pythonic/Pandaic approach to looping over a pandas Series

查看:82
本文介绍了更多Pythonic/Pandaic方法遍历 pandas 系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is most likely something very basic, but I can't figure it out. Suppose that I have a Series like this:

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

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

How can I do operations on sub-series of this Series without having to revert to using a for-loop?

例如,假设我要将其转换为包含四个元素的新系列.此新系列中的第一个元素是原始系列中前三个元素(1、1、1)的总和,第二个是后三个元素(2、2、2)的总和,等等.

Suppose, for example, that I want to turn it into a new Series that contains four elements. The first element in this new Series is the sum of the first three elements in the original Series (1, 1, 1), the second the sum of the second three (2, 2, 2), etc.:

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

我该怎么做?

推荐答案

您可以使用numpy重塑系列s1,然后对诸如以下的行求和:

You could reshape the series s1 using numpy and then sum over the rows such as:

np.sum(np.array(s1).reshape(len(s1)/3,3), axis = 1)

这将导致

array([ 3,  6,  9, 12], dtype=int64)

正如他的评论中提到的 MSeifert 一样,您还可以让numpy计算长度,例如:

as MSeifert mentioned in his comment, you can also let numpy compute the length such as:

np.sum(np.array(s1).reshape(-1, 3), axis=1)

这篇关于更多Pythonic/Pandaic方法遍历 pandas 系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆