【问题标题】:How to iterate over DataFrame to select rows如何遍历 DataFrame 以选择行
【发布时间】:2020-02-25 16:21:26
【问题描述】:

我是 Python 新手,我正在尝试了解如何从 Dataframe 中的每个索引中选择 n 行并构建一个仅包含选定行的新 Dataframe。

我的 df 看起来像这样:

      Col1 Col2 Col3 etc
   A
   A
   A
   A
   B
   B
   B
   B

我基本上会为每个索引取前两行:

     Col1 Col2 Col3 etc.
   A
   A
   B
   B

我尝试使用如下所示的 for 循环和 iloc 来执行此操作,但循环停止到索引 A:

   for i in df:
       sel=df.iloc[:3]

我知道这是一个基本问题,但我阅读的越多,我就越对 for、apply、range 等感到困惑

请帮忙!谢谢

【问题讨论】:

    标签: python pandas loops dataframe


    【解决方案1】:

    如果您想获取每个组的前两行,您可以执行以下操作:

    df.groupby('Col1').head(2)
    

    【讨论】:

      【解决方案2】:

      如果 A、B 等在索引中而不是在第一列中,@Chris 的答案会略有不同。你应该先重置索引,使用group_by,head,重置索引并去掉它的名字:

      df.reset_index().groupby('index').head(2).set_index('index').rename_axis(None)
      

      【讨论】:

        猜你喜欢
        • 2022-10-25
        • 2021-11-01
        • 2018-12-28
        • 2021-02-01
        • 2015-01-03
        • 2012-05-30
        • 2019-07-19
        相关资源
        最近更新 更多