Compare a variable to every element of an array - python

I am trying to compare a variable to the values that are stored in an array. The values in the array are extracted out from a csv file. If the values of the array are equal to the variable it will print out true.
import csv
array=[]
values = csv.reader(open('SampleEEG data Insight-1-30.11.15.17.36.16.csv', 'r'),
delimiter=',',
quotechar='|')
for row in values:
array.append(row[5])
number= 4200
for a in array:
if number == a:
print ('True')
print ('False')
The code only compares one value in the array and returns a false. How do I compare all the values in the array to the variable?

Use the all function with list comprehensions
number = 10
array = [1, 2, 3, 4]
print( all(number == a for a in array) )
# False
array = [10, 10, 10, 10]
print( all(number == a for a in array) )
# True

You can use all() - builtin function
all (number == a for a in array)

From what I could figure out from your comment, this is probably what you are looking for:
array=[]
with open('SampleEEG data Insight-1-30.11.15.17.36.16.csv', 'r') as file:
lines = [line.split() for line in file.readlines()]
for line in lines:
try:
array.append(float(line[5]))
except ValueError:
pass
number= 4200
for a in array:
if number == a:
print ('True')
print ('Done, all checked')

Because it is exiting from the loop after it hits the first true value. Use the following code:
for i in array:
if number == i:
print ('True')
else:
print ('False')

Related

Need to read numbers fromm file and store even numbers in an array and print it|| python program

f = open("LFx.txt", "r")
numbers=f.read(10)
array=[]
print(numbers)
for num in numbers:
if num%2==0:
array.append(num)
print(array)
I am getting type error everytime when i run this i dont now whats the problem is.Please Help me with this question.
numbers is a string, you need to transform the string into numbers.
suppose that you have the following data :
data = "1, 2, 1, 4"
then you can retrieve the numbers using
numbers = [int(value) for value in data.split(,)]
When you read from file it is in string format.
you need to type cast your data first and then do the operations.
you can try something like this:
f = open("LFx.txt", "r")
numbers=f.read(10)
array=[]
# here convert each number in string format to int
numbers = [int(i) for i in numbers.split() if i.isdigit()]
for num in numbers:
if num%2==0:
array.append(num)
print(array)
Can you provide some more information? How are the numbers stored in the file? line by line? all in one line? Seperated by commas? seperated by new line characters?
Reading the file will give you the stored information as a string, you can not execute mathematical operations between strings and integers.
this is invalid:
f = "1,2,3,4,5" #numbers read from your file
array = []
for num in f:
if num%2==0:
array.append(num)
print(array)
But this prints [2,4]:
f = 1,2,3,4,5
array = []
for num in f:
if num%2==0:
array.append(num)
print(array)
one solution would be:
import os
a = []
o = open("filename.txt","r")
y = o.read()
z = 0
for c in y.split():
a.append(int(c))
#now you can do mathematical operations on the elements in a
array = []
for num in a:
if num%2==0:
array.append(num)
print(array)

How to find the sum of a certain column in a .txt file in Python?

I have a .txt file with 3 rows and 3 columns of data shown below:
1.5 3.1425 blank
10 12 14
8.2 blank 9.5
I am looking to create a function that allows a user to input a number of either 1,2,or 3 and get the sum of that specified column
The error I receive is as follows:
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
summarizer(2)
File "/Users/"practice.py", line
403, in summarizer
print(sum(float(col2)))
ValueError: could not convert string to float: '.'
I'm just practicing my indexing and am running into trouble when trying to pick a specific column or row to analyze. I have the following code, but get errors pertaining to my index being out of range, or a float object not being iterable
def summarizer(searchNum):
infile = open('nums.txt','r')
fileContents = infile.readlines()
infile.close
newList = []
for numbers in fileContents:
numVals = numbers.split('\t')
for i in range(len(numVals)):
for j in range(0, len(numVals[i])):
newList+=numVals[i][j]
col1 = numVals[i][0]
col2 = numVals[i][1]
col3 = numVals[i][2]
if searchNum == 1:
print (sum(float(col1)))
elif searchNum == 2:
print(sum(float(col2)))
else:
print(sum(float(col3)))
If a user inputs summarizer(3), I would like the output to be 23.5 since 14+9.5+0= 23.5
I put comments on the script. You can create three column lists to collect each value in the corresponding columns. Then sum it at the end.
def summarizer(searchNum):
infile = open('nums.txt','r')
fileContents = infile.readlines()
infile.close
col1, col2, col3 = [], [], [] #initialize the columns
for numbers in fileContents:
numVals = numbers.replace('\n','').split('\t') #also remove newline at the end (\n)
col1.append(float(numVals[0]) if numVals[0] else 0) #convert to float if not blank else 0 then add to col1
col2.append(float(numVals[1]) if numVals[1] else 0)
col3.append(float(numVals[2]) if numVals[2] else 0)
if searchNum == 1:
print(sum(col1))
elif searchNum == 2:
print(sum(col2))
else:
print(sum(col3)) #print the sum of col3
return
Result:
summarizer(3)
23.5
You need to make sure that text file is perfectly formatted with tabs. Then you need to append each row to a list, and split each value by tabs.
Then you need to get rid of 'blanks' and '\n' or whatever other non-numbers.
Then sum them.
This is how I would do it
infile = open('nums.txt','r')
fileContents = infile.readlines()
infile.close
newList = [] # List of lists. Each list is a column
for line in fileContents:
newList.append(line.split('\t'))
# - Blank must be 0. Let's get rid of \n as well
for i in range(len(newList)):
for j in range(len(newList[i])):
if '\n' in newList[i][j]:
newList[i][j] = newList[i][j].replace('\n', '')
try:
newList[i][j] = float(newList[i][j]) # get rid of string entries
except ValueError:
newList[i][j] = 0
sum = 0
if searchNum == 1:
for i in range(len(newList)):
sum += newList[i][0]
if searchNum == 2:
for i in range(len(newList)):
sum += newList[i][1]
if searchNum == 3:
for i in range(len(newList)):
sum += newList[i][2]
print(sum)
Explanation of the "could not convert string to float: '.' " error:
col2 variable has a string "blank" (which is not a integer) .
When you apply float on a string which is not a integer ( in our case float(col2)) it throws the error which u mentioned.
What your code actually does:
1.It creates a n*n 2d array and puts all the elements from textfile to the 2d array.
2.You assign the last element in each column to variable col1,col2,col3
3.You apply sum operation on the last element in each column
What you were trying to do :
1.Create a n*n 2d array and puts all the elements from textfile to the 2d array.
2.Apply sum operation on each column element and display the result:
So ur code is not actually doing what you wanted to do.
I have written the below code which does wat u actually intended to do
Solution Code
def summarizer(searchNum):
infile = open('nums.txt','r')
fileContents = infile.readlines()
infile.close
newList = []
for numbers in fileContents:
# - replace the "blank" string and with 0 and makes every instance
#- float type
numbers =numbers.replace("blank","0").replace('\n','').split('\t')
# - creates the 2d array of the items from you text file
for i in range(1,len(numbers)+1):
newList[i].extend(float(numbers[i-1]))
# - prints the sum based on column index u wanted
print(sum(newList(searchNum)))
You can do this easier by using the csv library
https://docs.python.org/2/library/csv.html

how do I check for numbers in a matrix

I need to check if the numbers in gradescale is in my NxM matrix as a numpy array, if example the number 8 is in my matrix, I would like to append the number to a empty list and the row number to another list
So how do i check if the number in my matrix isn't in gradescale, i have tried different types of loops, but they dont work.
wrongNumber = []
Rows = []
gradeScale = np.array([-3,0,2,4,7,10,12])
if there is a number i matrix which is not i gradeScale
wrongNumber.append[number]
Rows.append[rownumber]
print("the grade {} in line {} is out of range",format(wrongNumber),
format(Rows))
You can use numpy.ndarray.shape to go through your rows.
for row in range(matrix.shape[0]):
for x in matrix[row]:
if x not in gradeScale:
wrongNumber.append(x)
Rows.append(row)
In addition, you do not use format correctly. Your print statement should be
print("The grade {} in line {} is out of range".format(wrongNumber, Rows))
The following post has some more information on formatting String formatting in Python .
Example
import numpy as np
wrongNumber = []
Rows = []
matrix = np.array([[1,2],[3,4],[5,6],[7,8]])
gradeScale = [1,3,4,5,8]
for row in range(matrix.shape[0]):
for x in matrix[row]:
if x not in gradeScale:
wrongNumber.append(x)
Rows.append(row)
print("The grades {} in lines {} (respectively) are out of range.".format(wrongNumber, Rows))
Output
The grades [2, 6, 7] in lines [0, 2, 3] (respectively) are out of range
Probably a for loop with enumerate() is what you are looking for.
Example:
for rowNumber, number in enumerate(matrix)
if number not in gradeScale:
wrongNumber.append[number]
Rows.append[rowNumber]

How to output all the indices of a value from an input file

I'm trying to find all the indices of a value in an input file. The program will accept the number to be searched for as 1st command line argument, and the name of the input file as the second argument. I'm having trouble to output the indices at which the value was found from the code below:
import sys
value = sys.argv[1]
file_name = sys.argv[2]
file = open(file_name, 'r')
print('The value of file \"{}\" to be searched:\n{}'.format(file_name, value))
for line in file.readlines():
curr_arr = []
for i in line.split(','):
curr_arr +=[int(i)]
def find_values(curr_arr, val):
found_indexes = []
sum = 0
for n in range(len(curr_arr)):
sum += curr_arr[n]
if curr_arr[n] == val:
found_indexes += [n]
sum = sum + 1
return found_indexes
print 'The index(s) of the occurrence of {} in {}: {}'.format(value, curr_arr, find_values(curr_arr, value))
And this is what I get:
a1.py 7 text.csv
The value of file "text.csv" to be searched:
7
The index(s) of the occurrence of 7 in [2, 3, 7, 9, 7, 3, 2]:
I'm supposed to get [2, 4] but it returns none. Could anyone help me with the code? Thank you
Your value is currently a string. You should cast to int so the comparison with items in the array which are ints can be True for matching items:
value = int(sys.argv[1])
Otherwise, if curr_arr[n] == val: ... is always False, and the found_indices list remains empty.
Besides, you can build the list much more elegantly using enumerate to generate indices alongside the items in a list comprehension.
found_indices = [i for i, x in curr_arr if x == value]

Python - delete strings that are float numbers

I have a file with lots of lines that contain numbers seperated by coma , on each line.
Some lines contain numbers that are float numbers ie: ['9.3']
i have been trying to delete those numbers from the list for about 1h~ but no luck. and whenever it tries to use int on a float number it gives error. Im not sure how to remove these floating numbers from the lines
the numbers: https://pastebin.com/7vveTxjW
this is what i've done so far:
with open('planets.txt','r') as f:
lst = []
temp = []
for line in f:
l = line.strip()
l = l.split(',')
for x in l:
if x == '':
l[l.index(x)] = 0
elif x == '\n' or x == '0':
print "removed value", l[l.index(x)]
del l[l.index(x)]
try:
temp.append([int(y) for y in l])
except ValueError:
pass
First off, modifying the list you are iterating over is a bad idea. A better idea might be to construct a new list from the elements that can be converted to an int.
def is_int(element):
try:
int(element)
except ValueError:
return False
return True
with open('planets.txt','r') as f:
lst = []
temp = []
for line in f:
l = line.strip().split(',')
temp.append([int(y) for y in l if is_int(y)])
If you want to include the float values' integral component, you can do:
def is_float(element):
try:
float(element)
except ValueError:
return False
return True
with open('planets.txt','r') as f:
lst = []
temp = []
for line in f:
l = line.strip().split(',')
temp.append([int(float(y)) for y in l if is_float(y)])
looks like youre over complicating it, once you have got all your numbers from the file to a list just run this
numbers=["8","9","10.5","11.1"]
intList=[]
for num in numbers:
try:
int_test=int(num)
intList.append(num)
except ValueError:
pass
just change my numbers list to your list name
You can just match digits followed by a point followed by more digits:
import re
output_list = []
input = open('input.txt', 'r')
for line in input:
if '.' not in line:
output_list.append(line)
else:
output_list.append(re.sub(r"(\d+\.\d+)", '', line))
print("Removed", re.search(r"(\d+\.\d+)", line).group(1))
I would keep the numbers as string and simply check if there is a 'dot' in each 'splitted item' to identify floats.
with open('planets.txt','r') as f:
for line in f:
line = ','.join([item for item in line.strip().split(',') if not '.' in item])
print(line)
# ... write to file ...
When you get a list that contains digits (for instance, ['1','2.3','4.5','1.0']) you can use the following
intDigits = [ i for i in digits if float(i) - int(float(i)) == 0]
Doing int() on a float shouldn't give an error. Maybe your 'float' is actually a string as you're reading from the file, because
int('9.3')
doesn't work but
int(9.3)
does.
Edit:
How about applying this function to every number
def intify(n):
if n == '':
return n
try:
return int(n)
except ValueError:
return int(float(n))
If you just need to remove floats this was the simplest method for me.
mixed = [1,float(1),2,3,4.3,5]
ints = [i for i in mixed if type(i) is not float]
Results in: [1, 2, 3, 5]

Categories