I'm new to Python, but I'm trying to learn. I'm trying to recreate a Matlab for loop in Python. The Matlab for loop looks like this:
for i = 2:(L-1)
Acceleration_RMT5_x(i-1) = (RMT5(i+1,1)-2*RMT5(i,1)+RMT5(i
1,1))/(1/FrameRate)^2;
end
The datatype is float64, and is a 288x1 vector. My Python so far is:
for i in RMT5x:
Acceleration_RMT5x = RMT5x[i+1] -2*RMT5x[i] +RMT5x[i-1]/(1/250)^2)
This gives me "invalid syntax".
What do I need to fix to resolve this error?
To raise something to a power in Python you need ** not ^
Also you are looping through the values of RMT5x but you are trying to use the value (i) as an index. Instead you want to loop through the index.
Acceleration_RMT5x = list()
for i in range(1, len(RMT5x)-1):
Acceleration_RMT5x.append(RMT5x[i+1] -2*RMT5x[i] +RMT5x[i-1]/(1./250)**2)
I would use a list comprehension:
import numpy as np
Acceleration_RMT5x = [np.power( (RMT5(i+1,1)-2*RMT5(i,1)+RMT5(i-1,1))/(1/FrameRate), 2)]
Related
Am trying to write an if condition in which I test on the standard deviation of several lists that are in a dictionary, The if statement that I did didn't work for me as you can see in the code :
a= {}
a[0] = [0.9907568097114563, 0.9913344979286194, 0.9907568097114563, 0.9913344979286194,
0.9907568097114563]
a[1] = [0.8538417220115662, 0.8526862859725952, 0.8411322832107544, 0.8659734129905701,
0.851530909538269]
a[n] = ...
if np.std(a[i] for i in range(len(a)) < 0.01 :
print("Early stopping here !")
I am not sure what you're trying to do, but you are calling an np.std on a generator "a[i] for i in range(len(a))", you have a syntax error (missing ')') and are using a dictionary like a list (which although might work, I don't recommend it). Consider using "any" for the if statement, you're code would look something like this:
import numpy as np
a= {}
a[0] = [0.9907568097114563, 0.9913344979286194, 0.9907568097114563, 0.9913344979286194,
0.9907568097114563]
a[1] = [0.8538417220115662, 0.8526862859725952, 0.8411322832107544, 0.8659734129905701,
0.851530909538269]
# a[n] = ...
if all([np.std(a[i]) < 0.01 for i in a.keys()]):
print("Early stopping here !")
if tests for… well, a condition—truthfulness of one expression.
You can get what you want in a few different ways—you can create a condition that checks multiple things (for which any() may or may not be useful), or maybe a loop with the single checks inside would be more helpful.
I have pred_data.txt as
19.08541,17.41787,16.59118,16.03507,15.68560
20.01880,18.21,19.48975,19.32,19.29945
17.32453,17.434,15.4253,12.422,11.4311
f=open('pred_data.txt','r')
for value in f:
exam=np.array(value)
pred=clf.predict(exam)
print(pred)
When I run this, I got
ValueError: could not convert string to float:'19.08541,17.41787,16.59118,16.03507,15.68560\n'
But when I try like this:example=np.array([19.08541,17.41787,16.59118,16.03507,15.68560])
pred=clf.predict(example)
I got the predicted output. How to access the data from the file to get output?
You should use the function "fromstring" from numpy.
I think in your case it should be something like:
f = open("pred_data.txt", 'r').read()
preds = np.fromstring(f, sep=",")
print(preds)
It's might not be the best way, but it's work.
See:
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.fromstring.html
I did not test this, but wouln't it help to split the line/value into an array beforehand?
I mean
for value in f:
exam=np.array(value.split(','))
...
This way it would be easier to convert a list if strings into a list of floats instead of converting a full line of floats as strings.
When you read a line from the file, it comes out as a str. So in your example this:
for value in f:
np.array(value)
Is the same as this:
np.array('19.08541,17.41787,16.59118,16.03507,15.68560\n')
You need to get rid of the \n with strip and break this into actual units using split:
values_strs = value.strip().split(',')
But that will leave you will a list of strs. It's better to cast those as well using float:
# This is a comprehension. It's a bit clearer and more obvious than
# calling `map(float, value.strip().split(','))`, but they boil down
# to a similar idea.
values_flt = [float(v) for v in value.strip().split(',')]
Altogether, you could just simplify to:
exam = np.array(float(v) for v in value.strip().split(','))
Use Numpy's loadtxt function.
import numpy as np
np_array = np.loadtxt('pre_data.txt', delimiter=',')
I am new to Python, not sure if it is a stupid way of doing this (coz I might have thousands of stocks code). I am trying to pass a list of stock code which there is a list of dataframe I created separately. I'd like to pass different dataframe, based on the arrary, into the function. Any suggestion on the best way to carry out this?
def ind (in_df):
in_df['CHG']= in_df['Open'] / in_df['Close']
return ;
STK = ['GOOG','TSLA','AAPL']
for index in range(len(STK)):
print (STK[index])
ind(pd.DataFrame[STK[index]])
You can write the loop like below. That way you don't have to invoke len or individual list element separately.
STK = ['GOOG','TSLA','AAPL']
for stockCode in STK:
print (stockCode)
ind(pd.DataFrame[stockCode])
I want to know that when I defined a multi-dimension variables in Gurobi, how can I extract all the value of the solution and organize them in to a Numpy array according to the original coordinate of the variable.
I have the following decision variables defined in Gurobi using Python API:
for i in range(N):
for t in range(M):
Station_Size[i,t] = m.addVar(ub=Q, name = 'Station_Size_%s_%s' %(i,t))
for j in range(N):
Admission[i,j,t] = m.addVar(ub = Arrival_Rate[t,i,j], obj=-1, name = 'Admission_Rate_%s_%s_%s' %(i,j,t))
Return[i,j,t] = m.addVar(name = 'Return_Rate_%s_%s_%s' %(i,j,t))
I have the problem solved and I have three dictionary:
Station_Size, Admission and Return
I know that the solution can be accessed as:
Station_Size[i,t].X, Admission[i,j,t].X and Return[i,j,t].X
I want to creat three Numpy array such that:
Array_Station_Size[i,t] = Station_Size[i,t].X
Array_Admission[i,j,t] = Admission[i,j,t].X
I can definitely do this by creating three loops and creat the Numpy Array element by element. It's do-able if the loop doesn't take a lot of time. But I just want to know if there is a better way to do this. Please comment if I did not make myself clear.
Assuming your model's name is m, do the following:
Array_Station_Size = m.getAttr('x', Station_Size)
which is a gurobipy.tupledict now.
see gurobi doc here
http://www.gurobi.com/documentation/8.1/quickstart_windows/py_results.html
I figured this problem out.
Do the following:
Array_Station_Size = np.array()
Array_Station_Size[i,] = [Station_Size[i,t].X for t in rang(T)]
please help me.
I have two-dimensional array example :
self.history = [['23295', u'0.0500', u'0.0700', u'0.0600', u'0.0600'],['23295', u'0.0500', u'0.0700', u'0.0600', u'0.0600']]
i try parsing him and get string but have syntax error, please advice.
for i in range(int(cac)):
returning = returning + "\""+str(date_arr[i])+","+ str(self.history[0 for x in range(len(self.history))][i])+"+"
in output i need have somethings like :
"somedate,'23295','23295'" + "somedate,u'0.0500',u'0.0500'" + "somedate,u'0.0700',u'0.0700'"...
You have to use two for loops:
for x in range(len(self.history)):
for i in range(int(cac)):
returning = returning + "\""+str(date_arr[i])+","+ str(self.history[x][i])+"+"
Note that your code [x for x in range(len(self.history))] generates a list whereas you need an integer to index your list