Converting a string to floats error - python

So I am trying to run this piece of code:
reader = list(csv.reader(open('mynew.csv', 'rb'), delimiter='\t'))
print reader[1]
number = [float(s) for s in reader[1]]
inside reader[1] i have the following values:
'5/1/2013 21:39:00.230', '46.09', '24.76', '0.70', '0.53', '27.92',
I am trying to store each one of values into an array like so:
number[0] = 46.09
number[1] = 24.09
and so on.....
My question is: how would i skip the date and the number following it and just store legitimate floats. Or store the contents in an array that are separated by comma?
It throws an error when I try to run the code above:
ValueError: invalid literal for float(): 5/1/2013 21:39:00.230
Thanks!

Just skip values which cannot be converted to float:
number = []
for s in reader[1]:
try:
number.append(float(s))
except ValueError:
pass

If it's always the first value that's not a float, you can take it out doing:
reader = list(csv.reader(open('mynew.csv', 'rb'), delimiter='\t'))
print reader[1]
number = [float(s) for s in reader[1][1:]]

Or you can search for / in the string and pass if exists, something like this
my_list_results = []
my_list = ['5/1/2013 21:39:00.230', '46.09', '24.76', '0.70', '0.53', '27.92']
for m in my_list:
if '/' not in m: #if we don't find /
my_list_results.append(m)
print my_list_results

number = []
for s in reader[1]:
number.append(int(float(s)))
this will convert string into exact float

Related

Transform multiple strings in integers

I am trying to transform into integers two strings (that are numbers) separated by a space, but I keep failing. I have tried numerous different solution, but nothing seems to work.
f= open('new.txt', 'r')
list_author = []
for line in f:
header1 = f.readline()
header2 = f.readline()
header3 = f.readline()
line = line.strip().replace('\t', ' ')
line=list(map(str,line.split()))
list_author.append([line])
print(list_author[1:10])
Output (formatted for readability):
[[['#', 'Directed', 'graph', '(each', 'unordered', 'pair', 'of', 'nodes', 'is', 'saved']],
[['3466', '937']],
[['3466', '15931']],
[['10310', '1854']],
[['10310', '9572']],
[['10310', '16310']],
[['10310', '24814']],
[['5052', '3096']],
[['5052', '5740']],
[['5052', '10235']]]
It seems that the first line is a header so you need to skip it. Then, you can use numbers = line.split("\t") on every line to have both numbers. Then you can add them into a the authorĀ“s list like this: list_author.append((int(number[0]),int(number[1])))
You can cast str to int using int("123") but i would be careful, your code will bomb out if you try to parse anything except an int, str or float and it must be a valid number, so you need to catch both TypeError and ValueError. I would wrap it in a function that you can call for each iteration:
def coerce(value: str) -> int or None:
try:
return int(value)
except (TypeError, ValueError):
# this is not convertible
return None

How to replace string character in Python?

for i in range(len(contents)):
contents = contents.replace(contents[i],chr(ord(contents[i]) + 1))
print(contents)
for i in range(len(contents)):
contents = contents.replace(contents[i],chr(ord(contents[i]) - 1))
print(contents)
This is where I get confused, shouldn't it just add 1 int to the character more and give you a character that is one byte (in UNICODE) above? Shouldn't it after you subtract one give you back the same result as before?
I have a string This is some sample text!. When I run the code, the string is converted to Ukkz%kz%zqoh%zboqmh%zhzz%.
Then, it should decrypt it back, but it show Tees es sole salole sess.
Thanks to #Jon Clements i have found a fix:
I converted the string into an array, then looped trough the array adding 1 to the character ordinal.
s = list(contents)
def encrypt(s):
for i in range(len(s)):
s[i] = chr(ord(s[i]) + 1)
ret = ''.join(s)
return ret
contents = "This is some sample text!"
print(f"Original value of contents: {contents}")
for i in range(len(contents)):
contents = contents[:i]+contents[i:].replace(contents[i],chr(ord(contents[i]) + 1),1)
print(f"Modified value of contents: {contents}")
for i in range(len(contents)):
contents = contents[:i]+contents[i:].replace(contents[i],chr(ord(contents[i]) - 1),1)
print(f"Reversed value of contents: {contents}")

Not all arguments converted

In Python, I am getting 'TypeError: not all arguments converted during string formatting'
I am not sure why this is happening. This line is being highlighted as where the problem lies - data.append('%s,%s,%s'%line['code'],line['level'],line['target'],line['distancefromtarget']
Can anybody find the problem?
In case it helps, here is the other code around this line.
def updatestocklevel(quantity, stocklevel, code):
with open('stockcontrol.csv',newline='') as f:
for line in f:
if code in line:
data = line.split(",")
target = (data[2])
updatetarget = int(target) - int(stocklevel)
newlevel = stocklevel - quantity
stocklevel = str(stocklevel)
newlevel = str(newlevel)
updatetarget = str(updatetarget)
import sys
import csv
data=[]
code = code
newval= newlevel
newtlevel = updatetarget
f=open("stockcontrol.csv")
reader=csv.DictReader(f,fieldnames=['code','level', 'target', 'distancefromtarget'])
for line in reader:
if line['code'] == code:
line['level']= newval
line['distancefromtarget']= newtlevel
data.append('%s,%s,%s'%(line['code'],line['level'],line['target'],line['distancefromtarget']))
f.close()
f=open("stockcontrol.csv","w")
f.write("\n".join(data))
f.close()
Thank You.
You've got a tuple with 4 elements:
(line['code'],line['level'],line['target'],line['distancefromtarget'])
But only 3 substitution placeholders:
'%s,%s,%s'
When you try to format that, not all of the "arguments" (tuple elements) will be converted to strings for the formatting (hence the error). Either change the tuple to remove an element, or change the string being interpolated to add another field (e.g. '%s,%s,%s,%s').

Single quotes around list elements that should be floats

I am asked to "return a list of tuples containing the subset name (as a string) and a list of floating point data values".
My code is:
def load_data(filename):
fileopen = open(filename)
result_open=[]
for line in fileopen:
answer = (line.strip().split(","))
result_open.append((answer[0],(answer[1:])))
return result_open
However, when I run the code, the following appears:
[('Slow Loris', [' 21.72', ' 29.3', ' 20.08', ' 29.98', ' 29.85', ' 26.22', ' 19......)]
Is there anyway to change the tuple to appear without the apostrophes? I want it to look like:
[('Slow Loris', [21.72, 29.3, 20.08, 29.98, 29.85, 6.22, 19......)]
line is a string, and line.strip().split(",") is a list of strings. You need to convert the string values into float or Decimal values. One way would be:
result_open.append((answer[0], [float(val) for val in answer[1:]]))
That will raise an exception on values that can't be converted to a float, so you should think about how you want to handle such input.

Python: Calculating the averages of values in a text file

When I run my code below I get a: ValueError: invalid literal for int() with base 10: '0.977759164126' but i dont know why
file_open = open("A1_B1_1000.txt", "r")
file_write = open ("average.txt", "w")
line = file_open.readlines()
list_of_lines = []
length = len(list_of_lines[0])
total = 0
for i in line:
values = i.split('\t')
list_of_lines.append(values)
count = 0
for j in list_of_lines:
count +=1
for k in range(0,count):
print k
list_of_lines[k].remove('\n')
for o in range(0,count):
for p in range(0,length):
print list_of_lines[p][o]
number = int(list_of_lines[p][o])
total + number
average = total/count
print average
My text file looks like:
0.977759164126 0.977759164126 0.977759164126 0.977759164126 0.977759164126
0.981717034466 0.981717034466 0.981717034466 0.981717034466 0.98171703446
The data series is in rows and the values are tab delimited in the text file. All the rows in the file are the same length.
The aim of the script is to calculate the average of each column and write the output to a text file.
int() is used for integers (numbers like 7, 12, 7965, 0, -21233). you probably need float()
Python is limited on handling floating points. These all work fine here but for longer ones as well as arithmetic you are going to want to use the Decimal module.
import Decimal
result = Decimal.Decimal(1)/Decimal.Decimal(5)
print result
Link to the documentation
http://docs.python.org/2/library/decimal.html
Try typing in 1.1 into IDLE and see what your result is.

Categories