I have a dataframe containing a variety of phone numbers that I want to extract the time zone for. I am apply to loop over the series in the dataframe as follows
external_calls_cleaned_df['time_zone'] = external_calls_cleaned_df.apply(lambda x: timezone.time_zones_for_number(phonenumbers.parse(str(x.external_number), None)), axis=1)
And this works just fine as long as the phone number in x.external_number doesn't contain a single invalid phone number; however, if one single invalid phone number is found in the entire series, it fails.
What I would like it to do is return 'Null' or None whenever it gets an invalid number- anything, actually - I can filter those out after the fact, but I don't want the process to stop at that point.
I have tried to wrap the timezone function in a new function and then execute it with try
def get_timezone(df):
try:
x = timezone.time_zones_for_number(phonenumbers.parse(str(df.external_number), None))
except:
None
return x
and then using
external_calls_cleaned_df['time_zone'] = external_calls_cleaned_df.apply(lambda x:get_timezone(x), axis=1)
The process completes then, but it fills the 'time_zone' field with None for every value.
To accomplish this I am using the phonenumbers package which is a port from the libphonenumber java package from google.
I can't share the phone numbers in my database for obvious reasons, so I don't know how to turn this into a reproducible example, or I would provide it.
Can anyone help me?
Thanks,
Brad
Try refactoring your code in order to use map with the target column "external_number" instead of apply with the whole dataframe, like this:
def get_timezone(x):
try:
return timezone.time_zones_for_number(phonenumbers.parse(str(x), None))
except:
return None
external_calls_cleaned_df["time_zone"] = external_calls_cleaned_df[
"external_number"
].map(get_timezone)
I have to say thank you in advance to whomever is helping me out here, I recently started learning python a fews days ago and a current problem set we are working on has been quite confusing.
I think it has to do with a fundamental misunderstanding of mine on how parameters are assigned within a function.
As I have briefly mentioned in title, I am being tasked with creating a function is_months_valid(months)
This is what I have done so far, brace yourselves:
def is_valid_month(month):
month = int
if month <= 0:
month == False
print('this is not a valid month')
if month >12:
month = False
print('this is not a valid month')
return month
As you can see what I am trying to do here is create an integer range from 1 to 12 where 'months' is a valid date.
The issue that I have been encountering is this:
'<=' not supported between instances of 'type' and 'int'
I.e a type error, and I think that my issue is that I am having trouble defining my parameter 'months' as an integer that can take any value. And this value, when run through my program presents me with a valid month or a print statement that says that
'this isnt a valid month'
Again, I am not sure how my code appears to anyone outside my perspective but I would appreciate any and all feedback on it.
Thank you
EDIT: Thank you guys my little frankenstein code finally works, for some reason I was under the assumption that in order to have my parameter (month) take any integer value I wanted, I needed to define it as an 'int.'
I know that stackoverflow isnt "help a student with his cs homework.com" but thank you all for your feedback regarding my indentation, the rules of python, and the guidance in the right direction. Coding is something that I want to improve on and hopefully become literate in.
Thank you
Maybe you meant that!
def is_valid_month(month):
if month <= 0:
month = False
print('this is not a valid month')
elif month >12:
month = False
print('this is not a valid month')
else:month=True
return month
Trying to fetch my Binance accounts order history with the python-binance module. There is an option to get all orders within one symbol (see documentation):
orders = client.get_all_orders(symbol='BNBBTC', limit=10)
Bu the problem is I can't pass more than 1coin in the symbol parameter
How can I pass a list for the symbol parameter, I want to fetch more than 1 coins order history in a single function
as I'm trying to build a portfolio for my Binance account. Or is there another method to do so?
Currently it is not possible to get all historical orders or trades without specifying the symbol in one call, even without the module python-binance.
There is an ongoing discussion on the Binance forum, requesting this feature.
As a workaround:
If you know your ordered symbols: Use the function get_all_orders() multiple times for each symbol in a loop.
If you don't know your ordered symbols: you could send a GET request for each symbol available at Binance (as mentioned in the discussion linked above). But be careful with the rateLimits.
I was asking myself the same thing. Well, a work around would be to iterate over all the tickers available in Binance looking for the ones we did traded in the past.
If you are working the free plan of the API, the best would be to setup a storage file or database and store all the result. Then you have to care about keeping with the changes from there.
Yeah, it is exactly how I am going to deal with this.
(edit) :
Sleep function will be needed to avoid more than 1200 queries per minute.
(example) :
def getAllTickers(self):
# Get all available exchange tickers
exchangeInfo = self.client.get_exchange_info()
# Extract the tickers general info
exchangeSymbols = []
for i in exchangeInfo['symbols']:
exchangeSymbols.append(i)
return exchangeSymbols
def getMyTrades(self, strSymbol):
return self.client.get_my_trades(symbol=strSymbol)
def getMyTradedTickers(self):
tickers = self.getAllTickers()
# Extract every ticker where trade happened
traded = []
for i in tickers:
tickerTransactions = self.getMyTrades(i["symbol"])
if tickerTransactions :
traded.append(tickerTransactions)
print(i["symbol"], " transactions available")
else :
print(i["symbol"], " has no transactions")
self.time.sleep(0.1)
return traded
**Srry for the code quality. Python is not my main coding language and im getting use to it.
I have a text file:
E5341,21/09/2015,C102,440,E,0
E5342,21/09/2015,C103,290,A,290
E5343,21/09/2015,C104,730,N,0
E5344,22/09/2015,C105,180,A,180
E5345,22/09/2015,C106,815,A,400
E5346,23/09/2015,C107,970,N,0
E5347,23/09/2015,C108,1050,E,0
E5348,23/09/2015,C109,370,A,200
E5349,25/09/2015,C110,480,A,250
E5350,25/09/2015,C111,330,A,330
E5351,25/09/2015,C112,1750,E,0
E5352,28/09/2015,C113,1500,N,0
E5353,28/09/2015,C114,272,A,200
E5354,29/09/2015,C115,560,E,0
E5355,29/09/2015,C116,530,A,450
E5356,29/09/2015,C117,860,E,0
E5357,29/09/2015,C118,650,E,0
E5358,29/09/2015,C119,380,A,380
E5359,29/09/2015,C120,980,N,0
E5360,30/09/2015,C121,1375,E,0
E5361,01/10/2015,C122,374,A,374
The E stands for the estimate number
The date following the estimate number is the estimated date
The C stands for the customer number
The number following the customer number is the final total in £
The letter after the final total tells you if the job was accepted(A) or not accepted (N) or the job was just an estimate (E)
The number after the status^ is the total amount already paid in £
I want to find out how if I enter one of the estimate numbers in python can I print out the date or work out the outstanding payments and find out what status the job is.
I've tried to research this but I don't understand it, I would really appreciate any help towards this.
The expected outcome if i put in the estimate number of 5353 is meant to show the date which would be 28/09/2015 for that example
The basic idea in Python 2 (note I have not tested this, but it should be close or work as is):
search = '5356' # supply this as your search
search = 'E'+search
fh = open('textfile.txt')
for line in fh:
elements = line.split(',')
if len(elements) == 6:
if elements[0] == search:
print 'For Estimate #'+search
print 'date:'+elements[1]
print 'cust:'+elements[2]
print 'totl:'+elements[3]
print 'stat:'+elements[4]
print 'paid:'+elements[5]
fh.close()
Now... go look up each statement in that example in the Python 2 documentation and see what the various items in it do. That'll give you a little kickstart towards learning the language, if you are ever going to do any more in it.
Keep in mind that failure is possible: What if the text file name is wrong, for instance, and the file open fails? You'll want to look at the try and except Python language elements.
Everyone needs to start somewhere, which is why I didn't give you a snarky "show your work" answer. So here's your start. Go forth and learn. :)
I'm trying to perform Sales Price to Cost calculations for a report. The data I'm getting is going into an Excel sheet to be passed along. The script has worked fine for weeks but recently started failing. It fails at a line that is writing data into my Excel sheet that takes two pieces of info and computes it to get my margin. The issue is my Cost isn't lower than my Sales Price (selling for a loss) and is cause my script to fail. How can I get my script to no only pass but record the equation correctly?
ws.cell(row=x, column=y, value=(s.SalePrice - s.Cost) / s.SalePrice)
I've imported pyxl and xlrd for my Excel sheets.
The error you get occurs whenever s.SalePrice is 0.
You can wrap your expression inside a try/except block to catch and handle that error appropriately:
try:
val = (s.SalePrice - s.Cost) / s.SalePrice
except ZeroDivisionError:
val = 'N/A'
ws.cell(row=x, column=y, value=val)
Replace N/A with any appropriate message you'd like to display in the event that s.SalePrice is 0.