I tried to add the comma seprated value between the : seprated then multiply the whole value
For example, consider my value is 1,2,3:4,5,6
I want to add the 1+2+3 ,and 4+5+6 then multiply the result of this value so answer is 6 * 15 = 90
For my bellow data i want the result is 7.224 but this script gives 61.658886435
I don't know what is the problem in my script'
ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
x_data = ar.split(":")
x_final = 1
x_add = 0
for i in x_data:
x_each = i.split(",")
for j in x_each:
x_add = x_add + float(j)
x_final = x_add * x_final
print x_final
Is any possible way to get the result without iterating loop? For above problem
This problem could be also solved in a functional way:
You have to multiply all values in the list - this is what functools.reduce + operator.mul for
You have to sum up all values in all inner lists - this is what sum for
Example:
In [5]: ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
In [6]: import operator
In [7]: import functools
In [8]: functools.reduce(operator.mul, (sum(float(x) for x in s.split(',')) for s in ar.split(':')))
Out[8]: 7.223521582500001
I don't necessarily recommend this complicated expression, but you can do it with list comprehensions and avoid the for loops:
import operator
ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
reduce(operator.mul, [sum([float(n) for n in e]) for e in [x.split(',') for x in ar.split(":")]], 1)
Use missed the initialize value as zero (x_add = 0) in each iterating. So your script add with the previous values
ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
x_data = ar.split(":")
x_final = 1
for i in x_data:
x_each = i.split(",")
x_add = 0 # Here you not initialize it
for j in x_each:
x_add = x_add + float(j)
x_final = x_add * x_final
print x_final
!!! As from #jpmc26 and #soon comment. Avoid using eval, and conform your input string format.
Without looping use regex for to do it
Use regex for solve your problem without looping.
ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
import re
ar = "("+ar #Add the ( with your data
ar = re.sub(r",","+",ar) #Substitute with + instead of ,
ar = re.sub(r"(?=\:|$)",")",ar) #look ahead for add `)` after colon
ar = re.sub(r"(?<=)\:","*(",ar) #Replace the color with *
#NOw you data look likes(0.212+1.231+0.112)*(1.001+3.212+0.002)*(0.002+0.0001+1.1)
#Finally evaluvate the string as a expression
print eval(ar)
Related
Took a large data set, removed any numbers that are not within 2 SD from a specific column and created an array, now I want to remove any numbers not in array from columns without messing up index. Would preferably like to convert any non-present numbers as nan.
Code used to remove values outside of 2 SD:
pupil_area_array = numpy.array(part_data['pupil_area'])
mean = numpy.mean(part_data['pupil_area'], axis=0)
sd = numpy.std(part_data['pupil_area'], axis=0)
final_list = [x for x in part_data['pupil_area'] if (x > mean - 2 * sd)]
final_list = [x for x in final_list if (x < mean + 2 * sd)]
print(final_list)
If you are not restricted to using a generator, you should be able to use map() https://www.geeksforgeeks.org/python-map-function/:
def filter_sd(value):
if x > mean - 2 * sd:
return x
return None #or return 'Nan'
final = map(filter_sd, part_data['pupil_area'])
I've managed to create a for-loop, which provides me with the results that I want, but I'm struggling to collate these results into a single array, so that I can plot it as my x value on a graph.
I have considered collating them into a single list first (but am also struggling to do this).
I have also tried to append, extend, and stack the array below, but nothing seems to work.
When trying to append, I got an error message appears to say that there is not 'value' present.
a = 0.1
x = 0.2
for i in range(1,10):
a = a**3
x = x**2
array = np.array ([a, x])
print (array)
The code above provides 9 individual arrays, as opposed to just 1.
i.e. [(a1, x1), (a2, x2), ... (a9, x9)]
Any suggestions to fix this or alternative methods would be greatly appreciated! Thank you!
okk so you want to store both variable values in this pattern (a1,x1),(a2,x2)....
So this can be done in this way
like first suppose two separate list for a and x , and then merge them into the desired format
the whole code is shown here
import numpy as np
a = 0.1
x = 0.2
list1= []
list2=[]
for i in range(1,10):
a = a**3
x = x**2
list1.append(a)
list2.append(x)
merged_list = [(list1[i], list2[i]) for i in range(0, len(list1))]
print(merged_list)
this will give you the desired output . Thanks for asking
Use append to append value in list
a = 0.1
x = 0.2
array = []
for i in range(1,10):
a = a**3
x = x**2
array.append([a, x])
print(array)
If you want numpy.array
a = np.power(np.repeat(0.1, 10), 3)
x = np.power(np.repeat(0.2, 10), 2)
print(np.array(list(zip(a,x))))
Do you want to append multiple items to a list?
First solution:
l = []
for i in range(1,10):
a = a**3
x = x**2
l.extend([a, x])
print(l)
Second solution:
l = []
for i in range(1,10):
a = a**3
x = x**2
l+= [a, x]
print(l)
Do you want to append multiple items to a numpy array?
array = np.array([])
for i in range(1,10):
a = a**3
x = x**2
array = np.append(array, [a,x])
print(array)
Here is what I want to accomplish :
a = 1235
My result r should calculate 1/2 + 2/(2*2) + 3/(2*2*2) + 5/(2*2*2*2), so
r will output 1.6875
I tried..
s = 123
l = list(map(int, str(s))) # converted into list
print(l)
y = [int(x)/(2**s.index(x)) for x in l]
print(y)
but it does not work.
Don't use index (slow and will return the first index over and over, which is wrong), just iterate on the index (plus 1) of the string using enumerate.
Then feed directly to sum.
BTW your code can be simplified to write this directly in one line:
y = sum(int(x)/(2**i) for i,x in enumerate(str(1235),1))
result:
1.6875
I was working on a problem where I ran into this issue.
import numpy as np
str_format = "%H:%M:%S"
a = 0
b = 0
i = 0
while(i <= 238 ):
try:
opening_time = data_dict['Open'][a]
opening_time = datetime.strptime(opening_time, str_format)
x = opening_time
closing_time = data_dict['Close'][b]
closing_time = datetime.strptime(closing_time, str_format)
y = closing_time
a = a + 1
b = b + 1
i = i + 1
s = [y - x]
opening_duration_list = np.array(s)
print(opening_duration_list)
except ValueError:
print("Variable opening Hours")
a = a + 1
b = b + 1
i = i + 1
In this code I'm trying to have it so that each time the loop repeats s = [Y - X] it will create a new value in the numpy array.
However, instead it's just created a single value with tonnes of rows. Does anyone have an idea on what I've messed up here and how I can fix it?
I'm not sure why you would need to use a numpy array for this. Regular arrays should be fine then you can cast to a numpy array if needs be. Here's a simple solution:
result = []
for i in range(0, len(data_dict['open'])):
try:
open_time = data_dict['open'][i]
closing_time = data_dict['closed'][i]
opening_duration = closing_time - opening_time
result.append(opening_duration)
except ValueError:
print("Variable opening hours")
final_result = np.array(result)
Some questions you might ask here are: What's your reasoning behind this ValueError loop? Why are these two arrays stored in a dictionary? If the values in the arrays returned by this dictionary differ by even one indices then they won't match each other? Wouldn't a better solution be to have a row for each store or day of whatever this is?
I'm having some troubles trying to use four lists with the zip function.
In particular, I'm getting the following error at line 36:
TypeError: zip argument #3 must support iteration
I've already read that it happens with not iterable objects, but I'm using it on two lists! And if I try use the zip only on the first 2 lists it works perfectly: I have problems only with the last two.
Someone has ideas on how to solve that? Many thanks!
import numpy
#setting initial values
R = 330
C = 0.1
f_T = 1/(2*numpy.pi*R*C)
w_T = 2*numpy.pi*f_T
n = 10
T = 1
w = (2*numpy.pi)/T
t = numpy.linspace(-2, 2, 100)
#making the lists c_k, w_k, a_k, phi_k
c_karray = []
w_karray = []
A_karray = []
phi_karray = []
#populating the lists
for k in range(1, n, 2):
c_k = 2/(k*numpy.pi)
w_k = k*w
A_k = 1/(numpy.sqrt(1+(w_k)**2))
phi_k = numpy.arctan(-w_k)
c_karray.append(c_k)
w_karray.append(w_k)
A_karray.append(A_k)
phi_karray.append(phi_k)
#making the function w(t)
w = []
#doing the sum for each t and populate w(t)
for i in t:
w_i = ([(A_k*c_k*numpy.sin(w_k*i+phi_k)) for c_k, w_k, A_k, phi_k in zip(c_karray, w_karray, A_k, phi_k)])
w.append(sum(w_i)
Probably you mistyped the last 2 elements in zip. They should be A_karray and phi_karray, because phi_k and A_k are single values.
My result for w is:
[-0.11741034896740517,
-0.099189027720991918,
-0.073206290274556718,
...
-0.089754003567358978,
-0.10828235682188027,
-0.1174103489674052]
HTH,
Germán.
I believe you want zip(c_karray, w_karray, A_karray, phi_karray). Additionally, you should produce this once, not each iteration of the for the loop.
Furthermore, you are not really making use of numpy. Try this instead of your loops.
d = numpy.arange(1, n, 2)
c_karray = 2/(d*numpy.pi)
w_karray = d*w
A_karray = 1/(numpy.sqrt(1+(w_karray)**2))
phi_karray = numpy.arctan(-w_karray)
w = (A_karray*c_karray*numpy.sin(w_karray*t[:,None]+phi_karray)).sum(axis=-1)