-1

I've been trying to get the maximum/minimum value from a text file, but I don't know how to only take the integer of the text, python always take the string in the text and give me an error. Here's an exemple of the text file enter image description here Thank you,

Rene12345
  • 1
  • 2

3 Answers3

0

You can find int values of your text using pandas.DataFrame.dtypes. Here is your data and I assume that you saved it as a test.txt file:

E1    10    14    15
E2    10    13    10
E3    20    17    18
E4    13    10    11
E5    12    20    12
E6    14    16    14
E7    13    12    08
E8    14    16    15

You can read the data using Pandas and then find the columns that contain int values. Then you can search for the maximum integer value:

import pandas as pd

df = pd.read_csv("test.txt" , delimiter="\s+" , header= None)

maximum = 0
for col in df.columns:
    if df.dtypes[col] == "int64":
        if max(df[col])>maximum:
            maximum = max(df[col])

Then if you try to print(maximum), you'll get this:

20

So the critical part is to check the type of members of each column of the DataFrame! If you try to print(df.dtypes), you'll get this:

0    object
1     int64
2     int64
3     int64
dtype: object

This means, the first column(which contained E1, E2, ..., E8) has an object type, and the other ones have an int64 type(which you're looking for).

Shayan
  • 5,165
  • 4
  • 16
  • 45
0

Don't use Pandas unless needed. There's a much cleaner, simpler solution:

# Open the file
with open("filename.txt") as file:  # edit file name here
    text = file.readlines()  # a list of strings, each representing a line


# Get the values
values_2d = [[int(j) for j in i.split()[1:]] for i in text]  # turn them into integers (ignoring the first column), but it's still two-dimensional
values = sum(values_2d, []) # turn into a 1-dimensional list
print(f"Maximum: {max(values)}, minimum: {min(values)}")  # output

It's somewhat inefficient in the sum(,[]) part, but that's only been used for brevity.

musava_ribica
  • 476
  • 1
  • 5
  • 18
Mous
  • 953
  • 3
  • 14
0

You haven't tagged or mentioned any libraries so I'm going to assume you want a solution in vanilla Python. Your file format is a bit unambiguous, which smallest integer do you want to find? If you want to get the smallest integer in each row separately, you can open the file, read the lines into a list and extract the integers out of it:

with open("file.txt", "r") as f:
    lines = f.readlines()

for line in lines:
    # Find the first spacebar in the line, then slice
    # it from there to the end, and remove trailing newline
    temp = line[line.index(' '):].strip()

    # Loop through each number, but since there are multiple
    # spaces between numbers, skip empty strings
    # This can be done more easier with regular expressions
    numbers = temp.split(' ')
    # Look up the filter function on Python docs to learn what it does
    numbers = filter(lambda x: (not not x) or x == '0', map(int, numbers))
    print(min(numbers), max(numbers))
musava_ribica
  • 476
  • 1
  • 5
  • 18
  • `temp` is not necessary. `split` already removes newline with the default separator and you can just slice the result. Just `numbers = line.split()[1:]`. Also what's the point of that `filter`? It is not asked for – Tomerikoo Mar 15 '22 at 20:19
  • 1
    Isn't `lambda x: not not x` just `bool`? – Mous Mar 15 '22 at 20:20
  • @Tomerikoo Filter is there to, well, filter the empty strings. Judging by the file OP attached, there might be multiple spaces between number. `.split()`ting that string would result in a list of multiple empty strings. Feel free to try it yourself. @Mous It is a bool, rather it is returing True for Truey values (which is, thanks for reminding, not a good idea if a number happens to be 0) – musava_ribica Mar 15 '22 at 20:23
  • I meant, isn't `bool(x)` always equal to `(lambda x:not not x)` for all x? The lambda is very marginally faster. – Mous Mar 15 '22 at 20:27
  • 1
    `split` with the default argument removes ***all*** whitespaces so no, you will not have empty strings... Try it yourself `"hello world".split()` gives `["hello", "world"]` – Tomerikoo Mar 16 '22 at 09:57