【问题标题】:python pandas shift next rows for valuespython pandas 移动下一行的值
【发布时间】:2017-08-09 14:04:30
【问题描述】:

我使用熊猫: 输入:

import pandas as pd
a=pd.Series([0,0,1,0,0,0,0])

输出:

0    0
1    0
2    1
3    0
4    0
5    0
6    0

我想以相同的值获取下一行的数据:

输出:

0    0
1    0
2    1
3    1
4    1
5    1
6    0

使用

a+a.shift(1)+a.shift(2)+a.shift(3)

我认为这不是一个聪明的解决方案 谁对此有聪明的解决方案

【问题讨论】:

    标签: python pandas shift


    【解决方案1】:

    你可以试试这个假设索引 6 也应该是值 1

    a=pd.Series([0,0,1,0,0,0,0])
    a.eq(1).cumsum()
    
    Out[19]: 
    0    0
    1    0
    2    1
    3    1
    4    1
    5    1
    6    1
    dtype: int32
    

    更新:多个值不等于 0。

    a=pd.Series([0,0,1,0,1,3,0])
    a.ne(0).cumsum()
    A=pd.DataFrame({'a':a,'Id':a.ne(0).cumsum()})
    A.groupby('Id').a.cumsum()
    
    
    Out[58]: 
    0    0
    1    0
    2    1
    3    1
    4    1
    5    3
    6    3
    

    或者你可以使用ffill

    a[a.eq(0)]=np.nan
    a.ffill().fillna(0)
    
    Out[64]: 
    0    0.0
    1    0.0
    2    1.0
    3    1.0
    4    1.0
    5    3.0
    6    3.0
    

    【讨论】:

    • 可以对cumsum 进行任何eq(1) 按位比较的理由吗?
    • @AlexanderMcFarlane 已更新。但你是对的,以前的方法不需要eq
    【解决方案2】:

    1 您可以过滤系列中的“您的”值 (SearchValue)。

    2 将数据序列重新索引为待说明的长度 (LengthOfIndex) 并向前填充“你的”给定次数 (LengthOfFillRange)

    3 再次用零填充它。

     import pandas as pd
     import numpy as np
     a=pd.Series([0,0,1,0,0,0,0])
     SearchValue       = 1
     LengthOfIndex     = 7
     LengthOfFillRange = 4
     a=a[a==SearchValue]\
         .reindex(np.linspace(1,LengthOfIndex,LengthOfIndex, dtype='int32'),
                  method='ffill',
                  limit=LengthOfFillRange)\
         .fillna(0)
    

    【讨论】:

      【解决方案3】:

      如果您只需要在某些限制下重复 2 个值系列,请使用 replace 用于 NaNs,然后使用 ffillfillna 使用方法 ffill),最后使用 fillna 用于将 NaNs 转换为原始值(必要时转换为 int):

      a=pd.Series([0,0,1,0,0,0,0,1,0,0,0,])
      print (a)
      0     0
      1     0
      2     1
      3     0
      4     0
      5     0
      6     0
      7     1
      8     0
      9     0
      10    0
      dtype: int64
      
      b= a.replace(0,np.nan).ffill(limit=2).fillna(0).astype(a.dtype)
      print (b)
      0     0
      1     0
      2     1
      3     1
      4     1
      5     0
      6     0
      7     1
      8     1
      9     1
      10    0
      dtype: int64
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-09
        • 1970-01-01
        • 2018-05-08
        • 1970-01-01
        • 2016-06-10
        • 2018-10-30
        • 2019-04-19
        • 1970-01-01
        相关资源
        最近更新 更多