Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting the maximum values of every column and storing those value to an array in python without pandas

I have a text file that looks like this:

12345
23451
11221
21219
11223
71231

I want to have an array of lengths (number_of_columns – 1) that will store the maximum values of each column respectively except for the last column.

So my output array for this above example will look something like: 7 3 4 5

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I don’t want to use pandas here. I am unable to understand how to proceed.

>Solution :

Use:

with open(datafile) as infile:
    # convert each line to an iterable of ints
    rows = (map(int, line.strip()) for line in infile)
    
    # find the maximum per col, exclude the last one
    *res, _ = (max(col) for col in zip(*rows))
    print(res)

Output

[7, 3, 4, 5]

As an alternative:

with open(datafile) as infile:
    # convert each line to an iterable of ints exclude the last one
    rows = (map(int, line.strip()[:-1]) for line in infile)

    # find the maximum per col,
    res = [max(col) for col in zip(*rows)]
    print(res)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading