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

如何选择数据帧中行的百分比

  •  2
  • Jesse  · 技术社区  · 7 年前

    在python中,我有一些数据帧的结构如下:

    0 0 0 0
    1 1 1 1
    2 2 2 2
    . . . .
    n n n n
    

    以下是我的尝试:

    df.iloc[int(len(df)*0.33):int(len(df)*0.66)]
    

    它确实工作,但感觉真的很混乱,更不用说强制ints。

    我想知道是否有一个更干净的方法来选择一个数据帧的百分比,因为到目前为止我在文档中找不到任何有用的命令。

    3 回复  |  直到 7 年前
        1
  •  2
  •   Mara    7 年前

    也可以在索引上使用numpy百分位数函数。当索引不是从零开始时,此方法也有效。

    df[(df.index>np.percentile(df.index, 33)) & (df.index<=np.percentile(df.index, 66))]
    
        2
  •  0
  •   Bharath M Shetty    7 年前

    写一个函数来完成你的任务

    def get_middle(df,percent):
    
        start = int(len(df)*percent)
        end = len(df) - start
    
        return df.iloc[start:end]
    
    get_middle(df,0.33)
    
        3
  •  0
  •   el_Rinaldo    7 年前

    df.iloc[(len(df)// 3) : (len(df) - len(df)// 3), :]
    

    df.iloc[(len(df)// 3) : (len(df)// 3 * 2), :]
    

    (len(df.index)// 3) : (len(df.index)// 3 * 2)

        4
  •  0
  •   Rajat Mishra    4 年前

    percentage=round(len(df)/100*70) 
    documents(train) = df.head(percentage)  
    test=df.iloc[percentage:len(df),:]