Converting Str to Integer - python

I get the following error: TypeError: list indices must be integers, not str on this line of code:
a= doc['coordinates']['coordinates']
This is reading records from a db, I would like to know how to convert this into an integer from str?
Thanks
EDIT:
doc['coordinates']['coordinates'] returns coordinate information from a mongoDB, where these are the fields. It returns the relevant information for the first ten times the program runs, then I get this error.

Look at what is happening here:
a= doc['coordinates']['coordinates']
First doc['coordinates'] is evaluated. This returns a list of coordinates, lets say [32.9,23.11].
Now you're trying to look up something in this list with the index 'coordinates'.
a = [32.9,32.11]['coordinates']
This is your list: [32.9,32.11]
Lists only have numerical indices, in this case: 0 and 1.
If you're trying to assign a list of coordinates to a variable, you could just do a = doc['coordinates'] or if you want an individual coordinate, doc['coordinates'][0]

Related

Python throwing ValueError: is not in list although it's there in list

I am populating a tuple by importing a CSV file in Python. Now when I try to get index of a value in that tuple, it gives Value error: is not in list although the value is present. Below is the code I am using along with the sample data.
Following is the content of csv
IsNonPO,ApprovedState,ApprovalRecords/0/Comment,ApprovalRecords/0/Comment.Date
I am using the following code
import csv
flist = [tuple(row) for row in csv.reader(open('D:\\result_IV.csv', 'rU'))]
print (flist)
x = flist.index('IsNonPO')
print(x)
Below is the output I get
[('IsNonPO', 'ApprovedState', 'ApprovalRecords/0/Comment','ApprovalRecords/0/Comment.Date']
File "C:/Users/abc/PycharmProjects/Default/first.py", line 10, in <module>
x = flist.index('IsNonPO')
ValueError: 'IsNonPO' is not in list
The problem here is, You are parsing CSV content in tuple and then storing that tuple in a list.
flist = [('IsNonPO', 'ApprovedState', 'ApprovalRecords/0/Comment','ApprovalRecords/0/Comment.Date')]
So to access the first row, use flist[0]
then to get the index of a value in tuple use:
flist[0].index('IsNonPO')
Just change line 10 to:
x = flist[0].index('IsNonPO')
You don't follow your data structure.
According to your code, what you get is a list of tuples. Each tuple represents one line, and each tuple item represents a value in the csv.
So for
IsNonPO,ApprovedState,ApprovalRecords/0/Comment,ApprovalRecords/0/Comment.Date
you should get
[('IsNonPO', 'ApprovedState', 'ApprovalRecords/0/Comment','ApprovalRecords/0/Comment.Date')]
(note the missing )after the closing ].
So indeed, the list doesn't contain the given string, but a tuple with the given string.
One approach could be
n, val = next((n, i) for n, i in enumerate(flist) if 'IsNonPO' in i)
which gives you the first item (and the tuple) which contains 'IsNonPO'.
Then you can proceed with getting the index of 'IsNonPO' in that tuple.
Of course, it depends on what you really want to achieve. If you always have only one row, yashjain12yj's answer would work as well.

ValueError: too many values to unpack in a list

In python I have a list like below
in_list =[u'test_1,testing_1', u'test_2,testing_2', u'test_3,testing_3']
I want to print the values in this list in a loop
for test, testing in input:
print test, testing
I get this error:
ValueError: too many values to unpack
What is the correct method?
You have a list of three values on the right side; you have only two variables on the left. Doing this assignment of a sequence (list, in your case) to a series of variables is called "unpacking". You must have a 1:1 correspondence between values and variables for this to work.
I think what you're trying to do is to iterate through comma-separated value pairs. Try something like the code below. Iterate through the three strings in your input list (use a different variable name: input is a built-in function). For each string, split it at the comma. This gives you a list of two values ... and those you can unpack.
for pair in input_list: # "input" is a built-in function; use a different name
test, testing = pair.split(',')
# continue with your coding

TypeError: 'float' object is not iterable trying to convert number to float

I realise this error has been posted several times on the website, but none of the solutions seem to work for my problem. I would like to invoke elements from my list (which consists of numbers between 0.0-1.0, and is called numbers) by index, originally owlready allows me to get classes from an ontology, I had to convert them a few times to obtain a value which is considered a subclass in the ontology (for example, 0.6).
I would also like to ask if this approach in converting classes name to numbers is the correct way of doing things. The elements in the first list (values) look like this: melanoma_color.0.6 (where melanoma_color is the class and 0.6 is the subclass) I'm only interested in the subclass - 0.6.
from owlready import *
onto_path.append("C:/Users/Angelo/Desktop/Ontologia")
onto = get_ontology("http://localhost:8080/Melanoma_Names.owl").load()
values = list()
stringValues = list()
numbers = list()
test_melanoma = onto.Melanoma_Colors
for item in onto.subclasses_of(test_melanoma):
values.append(item)
for item in values:
stringValues.append(str(item))
del stringValues[-1:]
for x in stringValues:
numbers = [ float(x) for x in stringValues]
print(list(numbers[0]))
Apparently, you cannot pass a float to list(). Try list((numbers[0],))
Edit: Why do you even do print(list(...))? You could just do print(numbers[0]).

getting TypeError: unsupported operand type(s) for -: 'list' and 'list' while doing Min max normalization in python

I have been working with Python for a couple of months..Now,I have to perform min-max normalization for a column of my dataset(.csv file) for which I get the above mentioned type error..I have tried a lot but it still persists..Correct values are retrieved for min and max functions but the types of the results are list rather than float/integer..
This is the line that causes error
for i in range(num):
normalized[i]=(krr[i]-min(krr)/(max(krr)-min(krr))
where krr is the column retrieved from the dataset.Please help.
I have a function "normal" which does the min-max normalization..
I have taken column values using eval as shown in code
def normal(self,arr,num):
print("------------------->entered Normalisation block----------------->")
for i in range(num):
# trr=eval(str(arr[i]))[0:-31]
self.krr[i]=map(float,eval(str(arr[i]))[0:-31]) //extracting one particular column
#mn=min(self.krr)
#mx=max(self.krr)
print(self.krr)
ls=min(self.krr)
hs=max(self.krr)
diff=hs-ls
for i in range(num):
normalized[i]=(self.krr[i]-ls)/diff
OK, so the key issue here is that you are working on a list of sublists, with each sublist containing one number.
If you look at your formula:
(krr[i]-min(krr)/(max(krr)-min(krr))
As you mention, python can deal with the max and min - it will return the sublist that contains the biggest/smallest number. (Though note that getting a list containing one number is very different to getting just the one number) However, subtraction and division between lists is not supported, hence your error message. So sooner or later, you need to get the values out of the sublists.
My recommendation is that immediately after you finish constructing krr, you add the following line to your code:
krr = [element[0] for element in krr]
which converts krr from a list of sublists, to a list of the first element of each sublist.
Edit:
An alternative that I think will work, and is more efficient, is to change
def normal(self,arr,num):
print("------------------->entered Normalisation block----------------->")
for i in range(num):
# trr=eval(str(arr[i]))[0:-31]
self.krr[i]=map(float,eval(str(arr[i]))[0:-31]) # This row
into this:
self.krr[i]=float(eval(str(arr[i]))[0:-31][0])
map applies float to each element of the following list, and creates a new list. Instead, we're asking for the first element of that list, and applying float directly to it. That float is assigned to the index in krr.
PS eval(str(arr[i]))[0:-31] looks rather scary - does eval really need to be invoked here?

change value 2d array in Python

I have an array with 20 values, but value 16 is incorrent and must be replaced with the correct value. How can I do that?
texture[16] = 'sky13.jpg'
That code does not work for some reason. The error is "'tuple' object does not support item assignment"
You're working with a tuple instead of a list. Convert it to a list first
texture = list(texture)
texture[16] = 'sky13.jpg
check what texture is
type(texture)
if it is tuple then convert it to list
textute = list(texture)
in python simple way to talk tuple object is immutable list object
more about differences is here What's the difference between lists and tuples?
Tuples in Python are **inmutable**, which means that you can't change the value once you assign it!
You need to convert the tuple to a list:
listOfTextures = list(texture)
And then you will be able to change the values you want to.

Categories