How would I go around of finding the maximum value every 13 rows in python?

Viewed 60

So the thing is that I have lets say the following data base:

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

Lets say the name of this data frame is df

So I want the code that for every 3 lines in this case(my case 13) to get the maximum, so out put would be somehting like this:

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

I was thinking of a for that did something like this

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

But doing this I get AttributeError: 'float' object has no attribute 'iloc'

So any ideas are welcomed Thank you

2 Answers

You can simply divide your list into sections of 3 by doing

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

Where a is a list containing values of column B. Output:

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

Then, find the max value of each block, and display the corresponding index. Using a loop, you can run through the list, find the index of the value, and print its index.

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

Use groupby on custom groupID and idxmax and loc. Use n as the number of rows you want to group

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
Related