python - 我将如何在 python 中找到每 13 行的最大值?

标签 python pandas dataframe for-loop

所以问题是我有以下数据库:

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' object has no attribute 'iloc'

欢迎任何想法,谢谢

最佳答案

在自定义 groupID 和 idxmaxloc 上使用 groupby。使用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

关于python - 我将如何在 python 中找到每 13 行的最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60497569/

相关文章:

python - 在分组的 Pandas 数据框中的最大值后删除行

python pandas时间序列年提取

python - 将数据框中某个值选择的行替换为数据框中某个值选择的另一行

python - 矢量化的局限性是什么?

python - QTreeView/QStandardItemModel 中选定的行

python - 如何在 xonsh 的 for 循环中运行 shell 命令?

python - 根据其他数据帧的条件创建数据帧

python - 将 Pandas 数据框写入 .txt 文件

python - 运行 Django 服务器时出错 - 空路径与其中任何一个都不匹配

python-3.x - 如何有效地分解数据?