sheaph
sheaph

Reputation: 199

Identifying the highest number in a row with Python

I have data in three columns as follows, I am trying to identify the position of the greatest value in each row (1,2,3) and also to ignore the rows where the greatest value occurs more than once. The script I have below will identify the highest value in each row but I am unable fix the other two issues. Any advise would be greatly appreciated!

0   3   3
3   3   3
3   3   3
0   3   3
3   4   3


data = open('file.csv', 'r')

rows = []
for line in data:
    row = [int(each) for each in line.split()]
    rows.append(row)

data.close()

columns = zip(*rows)


for index, column in enumerate(rows):
    print max(column)

Upvotes: 1

Views: 169

Answers (2)

B.A. Toresdahl
B.A. Toresdahl

Reputation: 3

Your can return a list, with a little less code using python's count. OP asked just for the index of the highest value, if unique.

    max_index = list()
    for i in a:
        if i.count(max(i))>1:
            max_index.append(None)
        else:
            max_index.append(i.index(max(i)))

This example returns [None, None, None, None, 1]

Upvotes: 0

MrAlexBailey
MrAlexBailey

Reputation: 5289

Since all of your rows in are in a list, you can loop over that list and use a few built-ins to find the information you want:

gvalues = []
for row in rows:
    highest = max(row)
    tally = row.count(highest)
    position = row.index(highest)

    if tally == 1:
        gvalues.append((highest, position))
    else:
        gvalues.append((None, None))

Once this is finished, you will have a list gvalues that containes tuples of highest value, position for each row. It will contain None, None for the rows where there are more than one of highest.

For the example you provided it will output [(None, None), (None, None), (None, None), (None, None), (4, 1)]

Upvotes: 3

Related Questions