More Pythonic/Pandaic approach to looping over a pandas Series

后端 未结 4 656
你的背包
你的背包 2021-01-02 17:56

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条回答
  •  不知归路
    2021-01-02 18:35

    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)
    

    which results in

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

    EDIT: 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)
    

提交回复
热议问题