Well
It was been like half an hour writting and rewritting this with no success:
Hope any caritative soul can help me with some wisdom
Heres the two pieces of code I have tried, the most basic ones I tried before did not work also:
I am triying to make 2 columns with this if else conditional, I cant really figure out whats going on...
vel_sign = []
ac_sign = []
for i in range(len(X_train)):
if (int(X_train['Velocidad'][i]) > 0) and (int(X_train['Aceleracion'][i]) > 0):
vel_sign.append(1)
ac_sign.append(1)
elif (int(X_train['Velocidad'][i]) > 0) and (int(X_train['Aceleracion'][i]) == 0):
vel_sign.append(1)
ac_sign.append(0)
elif (int(X_train['Velocidad'][i]) > 0) and (int(X_train['Aceleracion'][i]) < 0):
vel_sign.append(1)
ac_sign.append(-1)
else: pass
vel_sign = []
ac_sign = []
for i in range(len(X_train)):(
if (X_train['Velocidad'][i] > 0):
vel_sign.append(1)
if (X_train['Aceleracion'][i] > 0):
ac_sign.append(1)
elif (X_train['Aceleracion'][i] == 0):
ac_sign.append(0)
elif (X_train['Aceleracion'][i] < 0):
ac_sign.append(-1)
else:pass
elif (X_train['Velocidad'][i] == 0):
vel_sign.append(0)
if (X_train['Aceleracion'][i] > 0):
ac_sign.append(1)
elif (X_train['Aceleracion'][i] == 0):
ac_sign.append(0)
elif (X_train['Aceleracion'][i] < 0):
ac_sign.append(-1)
else: pass
elif (X_train['Velocidad'][i] < 0):
vel_sign.append(-1)
if (X_train['Aceleracion'][i] > 0):
ac_sign.append(1)
elif (X_train['Aceleracion'][i] == 0):
ac_sign.append(0)
elif (X_train['Aceleracion'][i] < 0):
ac_sign.append(-1)
else: pass
else: pass)
X_train['V_signo'] = vel_sign
X_train['A_signo'] = ac_sign
print(X_train.head())
The error is the following
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-39-d5c1cf0b654a> in <module>
2 ac_sign = []
3 for i in range(len(X_train)):
----> 4 if (int(X_train['Velocidad'][i]) > 0) and (int(X_train['Aceleracion'][i]) > 0):
5 vel_sign.append(1)
6 ac_sign.append(1)
/opt/conda/lib/python3.6/site-packages/pandas/core/series.py in __getitem__(self, key)
1069 key = com.apply_if_callable(key, self)
1070 try:
-> 1071 result = self.index.get_value(self, key)
1072
1073 if not is_scalar(result):
/opt/conda/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_value(self, series, key)
4728 k = self._convert_scalar_indexer(k, kind="getitem")
4729 try:
-> 4730 return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
4731 except KeyError as e1:
4732 if len(self) > 0 and (self.holds_integer() or self.is_boolean()):
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
KeyError: 3
THANKS!!!!!!!!!!!!!
I think I got an Answer,
But if anyone got a better one, I would like to hear it :D:D
def Signo(array):
result = []
for x in range(len(array)):
if array[x] > 0:
result.append(1)
elif array[x] == 0:
result.append(0)
else:
result.append(-1)
return result
df['Vel_signo'] = Signo(df['Velocidad'].to_numpy())
df['Ac_signo'] = Signo(df['Aceleracion'].to_numpy())
Related
from binance import Client
import os
def get_position_amt(bot, symbol):
get_position = bot.futures_position_information(symbol=symbol)
amt = float(get_position[0]['positionAmt'])
return amt
def close_all_position(bot, symbol):
print('close_all_position')
amt = get_position_amt(bot, symbol)
if amt > 0:
close_order = bot.futures_create_order(
symbol=symbol, side="SELL", type="MARKET", quantity=amt
)
print(close_order)
elif amt < 0:
close_order = bot.futures_create_order(
symbol=symbol, side="BUY", type="MARKET", quantity=abs(amt)
)
print(close_order)
else:
print("no position : amt is zero")
def lambda_handler(event, context):
bot = Client(api_key=os.environ.get('api_key'), api_secret=os.environ.get('api_sc'))
data = eval(event['body'])
side=data.get('side')
symbol=data.get('market')
amt = get_position_amt(bot, symbol)
if side == "BUY":
if amt < 0:
close_all_position(bot, symbol)
elif side == "SELL":
if amt > 0:
close_all_position(bot, symbol)
ord_type = data.get('ord_type')
if ord_type == 'limit':
order = bot.futures_create_order(
symbol=data.get('market'), side=data.get('side'), type="LIMIT", timeInForce='GTC', quantity=float(data.get('volume')), price=float(data.get('price'))
)
print(order)
elif ord_type == 'market':
order = bot.futures_create_order(
symbol=data.get('market'), side=data.get('side'), type="MARKET", quantity=float(data.get('volume'))
)
print(order)
elif ord_type == 'close':
close_all_position(bot, data.get('market'))
else:
raise ValueError
I need only 1 request but this invoke 4 different requests.
4 request IDs are all different so this means it's not an error.
I tried changing time limit and number of retrys on configuration but nothing happened.
I would appreciate it if anyone know how to handle this problem.
I am facing an error while running a github code. I think the code is perfect, But i think am facing some dependency issues. Can anyone tell me what could possible be the reason behind this error. I am using python 2.7.
from __future__ import division, print_function
.
.
def time_step(self, xt):
xt = np.reshape(xt, newshape=self.dimensions)
ret_val = 0.
self.buffer.append(xt)
self.present.time_step(xt)
if self.t >= self.buffer_len:
pst_xt = self.buffer[0]
self.past.time_step(pst_xt)
if self.t >= self.present.theta + self.past.theta:
ret_val = self.comparison_function(self.present, self.past,
self.present.alpha)
self.ma_window.append(ret_val)
if self.t % self.ma_recalc_delay == 0:
self.anomaly_mean = bn.nanmean(self.ma_window)
self.anomaly_std = bn.nanstd(self.ma_window, ddof=self.ddof)
if self.anomaly_std is None or self.t < len(self.ma_window):
anomaly_density = 0
else:
normalized_score = (ret_val - self.anomaly_mean)/self.anomaly_std
if -4 <= normalized_score <= 4:
anomaly_density = CDF_TABLE[round(normalized_score, 3)]
elif normalized_score > 4:
anomaly_density = 1.
else:
anomaly_density = 0.
self.t += 1
return ret_val, anomaly_density
The code line which is giving error is the following,
normalized_score = (ret_val - self.anomaly_mean)/self.anomaly_std
Wrap it in try except, I used 0 as except value but you can change it per your needs:
try:
normalized_score = (ret_val - self.anomaly_mean)/self.anomaly_std
except ZeroDivisionError:
normalized_score = 0
I am currently implementing the LTE physical layer in Python (ver 2.7.7).
For the qpsk, 16qam and 64qam modulation I would like to know which is more efficient to use between an integer comparison and a list comparison:
Integer comparison: bit_pair as an integer value before comparison
# QPSK - TS 36.211 V12.2.0, section 7.1.2, Table 7.1.2-1
def mp_qpsk(self):
r = []
for i in range(self.nbits/2):
bit_pair = (self.sbits[i*2] << 1) | self.sbits[i*2+1]
if bit_pair == 0:
r.append(complex(1/math.sqrt(2),1/math.sqrt(2)))
elif bit_pair == 1:
r.append(complex(1/math.sqrt(2),-1/math.sqrt(2)))
elif bit_pair == 2:
r.append(complex(-1/math.sqrt(2),1/math.sqrt(2)))
elif bit_pair == 3:
r.append(complex(-1/math.sqrt(2),-1/math.sqrt(2)))
return r
List comparison: bit_pair as a list before comparison
# QPSK - TS 36.211 V12.2.0, section 7.1.2, Table 7.1.2-1
def mp_qpsk(self):
r = []
for i in range(self.nbits/2):
bit_pair = self.sbits[i*2:i*2+2]
if bit_pair == [0,0]:
r.append(complex(1/math.sqrt(2),1/math.sqrt(2)))
elif bit_pair == [0,1]:
r.append(complex(1/math.sqrt(2),-1/math.sqrt(2)))
elif bit_pair == [1,0]:
r.append(complex(-1/math.sqrt(2),1/math.sqrt(2)))
elif bit_pair == [1,1]:
r.append(complex(-1/math.sqrt(2),-1/math.sqrt(2)))
return r
Thanks
I want to input a string of five numbers with spaces between them and use raw_input() for it. However the second item(the portion that's between the first and second spaces) is claimed to be a syntax error. Code below:
#class for final output - used as an ad hoc static string
class StatString:
outstring = ""
#function to check if Boom or Trach or both
def BoomTrach(num,B,T):
Boom = False
Trach = False
temp = num
while temp != 0:
if num % B == 0:
Boom == True
break
if (temp % 10) % B == 0:
Boom = True
break
temp = (temp - temp % 10) / 10
temp = num
while temp != 0:
if num % T == 0:
Trach = True
break
if (temp % 10) % T == 0:
Trach = True
break
temp = (temp - temp % 10) / 10
if Boom and Trach:
herestring.outstring = herestring.outstring + "Boom-Trach"
elif Boom:
herestring.outstring = herestring.outstring + "Boom"
elif Trach:
herestring.outstring = herestring.outstring + "Trach"
else:
herestring.outstring = herestring.outstring + str(num)
#start of "main" portion
def main():
inS = raw_input() <<<--- Input here
arr = inS.split(' ')
X = int(arr[0])
Y = int(arr[1])
CountFrom = int(arr[2])
jump = int(arr[3])
CountUntil = int(arr[4])
#variable for error check
error = False
#checking for errors
if X < 1 or X > 9 or Y < 1 or Y > 9:
print "X and Y must be between 1 and 9"
error = True
if jump == 0:
print "jump cannot be 0"
error = True
elif (CountUntil - CountFrom) % jump != 0:
print "cannot jump from %d to %d",CountFrom,CountUntil
error = True
if error:
exit()
if CountFrom < 0 and CountUntil < 0 and jump > 0:
jump = jump * (-1)
herestring = StatString()
while CountFrom != CountUntil:
BoomTrach(CountFrom,X,Y)
CountFrom = CountFrom + jump
if(CountFrom != CountUntil):
herestring.outstring = herestring.outstring + ","
print herestring.outstring
error message: (the second 1 was marked as the source of the error)
>>> 1 1 1 1 1
SyntaxError: invalid syntax
>>>
I know what happened. You just run this module, and you thought that you start running it from the main function (like in C for example).
There is no problem with the raw_input line (the first line of the input). The problem is that your module does not try to read anything! You just typed "1 1 1 1 1" which is of course syntax error...
Append to your code this line to run the main function:
main()
You can also write the code of the main function not in some function, to get the same effect.
I am programming a Tic-Tac-Toe game. I have most of the program done. But I keep getting the following error and I don't understand what I am doing wrong. I have tried formatting it differently.
Traceback (most recent call last):
File "C:/Users/Akshay Sastry/Documents/CS 303E/Tic-Tac-Toe.py", line 66, in <module>
main()
File "C:/Users/Akshay Sastry/Documents/CS 303E/Tic-Tac-Toe.py", line 3, in main
while isWinner(board) == 0 and movesLeft(board) == True:
File "C:/Users/Akshay Sastry/Documents/CS 303E/Tic-Tac-Toe.py", line 20, in isWinner
if (b[0][0]=='x') and (b[0][0]==b[0][1]==b[0][2]):
TypeError: 'NoneType' object has no attribute '__getitem__'
This is my code:
def main():
board = makeBoard()
while isWinner(board) == 0 and movesLeft(board) == True:
printBoard(board)
p1row, p1col = input("Enter a row and column for x: ")
board[p1row][p1col] = 'x'
if isWinner(board) == 0 and movesLeft(board) == True:
printBoard(board)
p2row, p2col = input("Enter a row and column for o: ")
board[p2row][p2col] = 'o'
if isWinner(board) != 0:
print isWinner(board), 'won!'
else:
print 'Tie game.'
def makeBoard():
board = [['*','*','*'],['*','*','*'],['*','*','*']]
def isWinner(b):
if (b[0][0]=='x') and (b[0][0]==b[0][1]==b[0][2]):
return 'x'
elif (b[1][0]=='x') and (b[1][0]==b[1][1]==b[1][2]):
return 'x'
elif (b[2][0]=='x') and (b[2][0]==b[1][1]==b[2][2]):
return 'x'
elif (b[0][0]=='x') and (b[0][0]==b[1][0]==b[2][0]):
return 'x'
elif (b[0][1]=='x') and (b[0][1]==b[1][1]==b[2][1]):
return 'x'
elif (b[0][2]=='x') and (b[0][2]==b[1][2]==b[2][2]):
return 'x'
elif (b[0][0]=='x') and (b[0][0]==b[1][1]==b[2][2]):
return 'x'
elif (b[0][2]=='x') and (b[0][2]==b[1][1]==b[2][0]):
return 'x'
elif (b[0][0]=='o') and (b[0][0]==b[0][1]==b[0][2]):
return 'o'
elif (b[1][0]=='o') and (b[1][0]==b[1][1]==b[1][2]):
return 'o'
elif (b[2][0]=='o') and (b[2][0]==b[1][1]==b[2][2]):
return 'o'
elif (b[0][0]=='o') and (b[0][0]==b[1][0]==b[2][0]):
return 'o'
elif (b[0][1]=='o') and (b[0][1]==b[1][1]==b[2][1]):
return 'o'
elif (b[0][2]=='o') and (b[0][2]==b[1][2]==b[2][2]):
return 'o'
elif (b[0][0]=='o') and (b[0][0]==b[1][1]==b[2][2]):
return 'o'
elif (b[0][2]=='o') and (b[0][2]==b[1][1]==b[2][0]):
return 'o'
else:
return 0
def printBoard(board):
for i in range(3):
for j in range(3):
print board[i][j],
print
def movesLeft(board):
if board[0].count("*") != 0 or board[1].count("*") != 0 or board[2].count("*") != 0:
return True
else:
return False
main()
Your makeBoard() function returns None. You should make it like this:
def makeBoard():
return [['*','*','*'],['*','*','*'],['*','*','*']]
Your isWinner function can be made 3x smaller, as follows
def isWinner(b):
for i in range(3):
if (b[i][0] != '*') and (b[i][0]==b[i][1]==b[i][2]): # all rows
return b[i][0]
if (b[0][i] != '*') and (b[0][i]==b[1][i]==b[2][i]): # all cols
return b[0][i]
if (b[0][0] != '*') and (b[0][0]==b[1][1]==b[2][2]): # tl-br diag
return b[0][0]
elif (b[0][2] != '*') and (b[0][2]==b[1][1]==b[2][0]): # bl-tr diag
return b[0][2]
else:
return 0
For a larger board such as connect 4, however, you'd iterate over all points on the board and write a method that checked in a loop an arbitrary distance in every direction, rather than hard-coding every place a row can be in.