代码之家  ›  专栏  ›  技术社区  ›  RustyShackleford

如何从数据帧中提取每N行?

  •  1
  • RustyShackleford  · 技术社区  · 7 年前

    我有一个DF:

    如下所示(跳过许多行):

           id    
    201    1
    202    2
    203    3
    301    4
    303    5
    401    6
    

    我只想选择 x01st 这意味着需要201、301、401、501行用于整个数据帧。

    我试过这个:

    if df.index % 100 = 1:
        not sure what to do
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   jezrael    7 年前

    你很亲密,需要违约 RangeIndex 通过比较 1 :

    df1 = [df.index % 100 == 1]
    

    具有常规索引的解决方案:

    df1 = [np.arange(len(df)) % 100 == 1]
    

    如果想要也省略 1. 101. 排:

    df2 = (df[(df.index % 100 == 1) & (df.index > 200)]
    

    还有:

    a = np.arange(len(df))
    df2 = df[(a % 100 == 1) & (a > 200)]
    

    样品 :

    np.random.seed(100)
    df = pd.DataFrame(np.random.randint(10, size=(1000,3)), columns=list('ABC'))
    #print (df)
    
    a = np.arange(len(df))
    df2 = df[(a % 100 == 1) & (a > 200)]
    print (df2)
         A  B  C
    201  4  4  4
    301  1  3  2
    401  0  3  5
    501  5  8  4
    601  3  7  9
    701  5  5  7
    801  4  1  0
    901  4  7  6