代码之家  ›  专栏  ›  技术社区  ›  Pandas INC

如何在python中每13行查找一个最大值?

  •  0
  • Pandas INC  · 技术社区  · 6 年前

    所以我要说的是以下数据库:

    A B
    1 5
    2 6 
    3 7
    4 1
    5 4
    6 3
    7 5 
    8 8 
    9 5
    

    假设这个数据帧的名称是df

    所以我想让代码在这个例子(我的例子13)中每3行得到最大值,所以输出应该是这样的:

    row 3 has a max of 7 
    row 5 has a max of 4 
    row 8 has a max of 8 
    

    count = 0
    count1 = 3
    for vals in df[B]:
        max = max(vals.iloc[count:count1])
        count = count + 3
        count1 = count1 + 3
        print(max)
    

    但这样做会得到AttributeError:“float”对象没有属性“iloc”

    欢迎有任何想法谢谢

    2 回复  |  直到 6 年前
        1
  •  2
  •   Andy L.    6 年前

    使用 groupby 自定义groupID和 idxmax loc n 作为要分组的行数

    n = 3
    df_out = df.loc[df.groupby(np.arange(len(df)) // n).B.idxmax()]
    
    Out[1201]:
       A  B
    2  3  7
    4  5  4
    7  8  8
    
        2
  •  2
  •   nagyl    6 年前

    a = [[a[i], a[i+1], a[i+2]] for i in range(0, len(a), 3)]
    

    [[5, 6, 7], [1, 4, 3], [5, 8, 5]]
    

    然后,找到每个块的最大值,并显示相应的索引。使用循环,可以遍历列表,找到值的索引,并打印其索引。

    slice = 0
    for i in range(len(a)):
        "row {} has a max of {} ".format(slice + a[i].index(max(a[i])), max(a[i]))
        slice = slice + 3