Selecting more than 1 F'string in dataframe. python? - python

I have a sample code using google calendar API that requires data to be a string value. Instead of manually typing strings each time the data frame is changed I use df.iat. This is what I have so far and works fine for a single value.
Create an event
"""
event = {
'summary':f'{df.iat[0,0]}',
'description': f'{df.iat[0,1]}',
'start': {
'date': '2022-04-04',
},
'end': {
'date': '2022-04-04',
which prints out
summary = Order
description = Plastic Cups
date 04-04-2022
But I need to pull multiple values into a string. How do I perform this to work properly
for example in the description
I want to do f'{df.iat[1,1]}',f'{df.iat[0,1]}'
which would print out description = 7000 Plastic Cups
but I get errors using this and I've tried dfiloc, I've also tried just a sample
(("test"),(f'{df.iat[0,1]}')
this only prints off the 'test' portion and not the df.iat string
I've been stuck at this for hours any help would be appreciated.

f-strings in Python, also known as Literal String Interpolation, can handle multiple variables at the same time. For example:
orderID = 012345
orderName = "foo"
message = f"Your order {orderName} with orderID {orderID} was registered!"
If you print the aforementioned message variable:
Your order foo with orderID 012345 was registered!
For more info regarding this: PEP-0498

Related

Is there a Coingecko Python API function to query coins based on their 3 letter abbreviation symbol?

I am utilizing the coingecko python API, and I want to query bitcoin and other coins price using their symbols like 'BTC' and 'ETH'.
Currently can query with
prices['BTC'] = cg.get_price(ids='bitcoin', vs_currencies='usd')['bitcoin']['usd']
prices['ETH'] = cg.get_price(ids='eth', vs_currencies='usd')['bitcoin']['usd']
However, is there a function for cg python that will let me use the 3 letter abbreviation for the coins?
i've been wondering the same thing too. There doesn't seem to be any standardization for the id field...even having to discern whether to use yearn, or yearn-finance, or yearn.finance, etc is not very ideal...
coin_list = cg.get_coins_list()
d = {}
for coin in coin_list:
d[coin['symbol']] = coin['id']
# now use d['btc'] to search
prices['BTC'] = cg.get_price(ids=d['btc'], vs_currencies='usd')['bitcoin']['usd']
prices['ETH'] = cg.get_price(ids=d['eth'], vs_currencies='usd')['bitcoin']['usd']

When using pygal.maps.world is there a way to format the numbers that display a country's population?

I am using pygal to make an interactive map showing world country populations from 2010. I am trying to find a way so that the populations of the country display with commas inserted ie as 10,000 not simply 10000.
I have already tried using "{:,}".format(x) when reading the numbers into my lists for the different population levels, but it causes an error. I believe this to be because this changes the value to a string.
I also tried inserting a piece of code I found online
wm.value_formatter = lambda x: "{:,}".format(x).
This doesn't cause any errors but doesn't fix how the numbers are formatted either. I am hoping someone might know of a built in function such as:
wm_style = RotateStyle('#336699')
Which is letting me set a color scheme.
Below is a the part of my code which is plotting the map.
wm = World()
wm.force_uri_protocol = "http"
wm_style = RotateStyle('#996699')
wm.value_formatter = lambda x: "{:,}".format(x)
wm.value_formatter = lambda y: "{:,}".format(y)
wm = World(style=wm_style)
wm.title = "Country populations year 2010"
wm.add('0-10 million', cc_pop_low)
wm.add("10m to 1 billion", cc_pop_mid)
wm.add('Over 1 billion', cc_pop_high)
wm.render_to_file('world_population.svg')
Setting the value_formatter property will change the label format, but in your code you recreate the World object after setting the property. This newly created object will have the default value formatter. You can also remove one of the lines setting the value_formatter property as they both achieve the same thing.
Re-ordering the code will fix your problem:
wm_style = RotateStyle('#996699')
wm = World(style=wm_style)
wm.value_formatter = lambda x: "{:,}".format(x)
wm.force_uri_protocol = "http"
wm.title = "Country populations year 2010"
wm.add('0-10 million', cc_pop_low)
wm.add("10m to 1 billion", cc_pop_mid)
wm.add('Over 1 billion', cc_pop_high)
wm.render_to_file('world_population.svg')

JSON string extraction into field

Im getting this JSON extract using scrapy, but the desc has the amunt and the amount type on in, this could be g, gr, kg, L, etc. I wan't to know if its possible to extract this data and add it into an additional field.
How could this be achievable either within scrapy or a separate process once he file has been created.
P.S. I'm totally new to JSON and scrapy and I'm learning.
Current
{
'p_desc': ['Coffee 225 g '],
'p_price': ['8.00']
}
Desired
{
'p_desc': ['Coffee'],
'p_amount': [225]
'p_amount_type': ['g']
'p_price': ['8.00']
}
Something like this works if the data has a regular structure (i.e. every desc contains amount and amount type as the last two fields). If not you might have to use regular expressions.
One observation: if each value is unique you don't need a list and for instance you can just use 'Coffee' instead of ['Coffee']
jsonData = {
'p_desc': ['Grain Black Coffee 225 g'],
'p_price': ['8.00']
}
var p_desc, p_amount, p_amount_type;
[p_amount_type, p_amount,...p_desc] = jsonData['p_desc'][0].split(" ").reverse();
jsonData["p_amount"] = [p_amount];
jsonData["p_amount_type"] = [p_amount_type];
jsonData["p_desc"] = p_desc.join(' ');
console.log(jsonData);
Also, you might need to remove trailing white-space from the description.

Assigning Values to a Dictionary of Tables

I have a situation in which Sales Managers reply to an automated email with lead times for primary and secondary leads. Their response would include a indication of which type of lead it was and the lead time. For example:
Primary_Lead 10
Secondary_Lead 20
I wrote a script to look through the emails (based on a certain subject) and find the lead times in the response. I want to add these to the Lead_Time dictionary of tables. I think everything works fine except for my last two lines which append values to Sales Manager and Lead Time. What am I doing wrong here? I know the whole email thing adds an additional level of complication that I don't need assistance with but wanted to provide actual code.
import win32com.client
import re
olFolderInbox = 6
olMailItem = 0
outlook = win32com.client.Dispatch("Outlook.Application")
mapi = outlook.GetNamespace('MAPI')
inbox = mapi.GetDefaultFolder(olFolderInbox)
My_Folder = inbox.Folders("Leads")
Lead_Time = {
'Primary_Leads': {'Sales Manager' : [],'Lead Time' : []},
'Secondary_Leads': {'Sales Manager' : [],'Lead Time' : []}
}
for i in range (My_Folder.Items.Count): #loops through all emails in Leads Folder
message = My_Folder.Items[i] #sets the message
if "RE: Lead Time Report" in message.Subject: #checks for a certain subject
for tbl in Lead_Time:
if tbl.upper() in message.Body.upper():
tbl['Sales Manager'].append map(int,re.findall(tbl +"* (\d+)",message.Body,re.I))
tbl['Lead Time'].append message.sender
You are iterating over the keys of Lead_Time when you really want to append to the values.
You can see this confusion in your own code:
for tbl in Lead_Time:
if tbl.upper() in message.Body.upper():
tbl['Sales Manager'].append
On the second line you treat tbl as the string that it is. On the third line you treat tbl like the array value associated with it in the dictionary.
You could change your code as follows:
Lead_Time[tbl]['Sales Manager'].append ...
Lead_Time[tbl]['Lead Time'].append ...
Or you could ask for both the key and the value when iterating:
for table_name, value in Lead_Time.items():
if table_name.upper() in message.Body.upper():
value['Sales Manager'].append ...
You can see the output of the default dict iterator with this much simpler example:
some_dict = {1: 2, 3: 4}
for key in some_dict:
print key
This prints 1 and 3.

How to filter domain data python opnerp 7?

how to filter domain data when my xml is,
xml code: <field name="categ_temps" domain="[('parent_id', '=', 1)]" on_change="myProduct_Category_OnChange(categ_temps)" sequence="1"/>
it is getting value App product/phone i want to remove "All product" from it how would i split it?
more over i am using onchange method that is,
python code : def myProduct_Category_OnChange(self,cr,uid,ids,categ_temps):
pro_id=[]
if(str(categ_temps)!='False'):
cr.execute('select id,name from product_category where parent_id='+str(categ_temps))
res = cr.fetchall()
for pid,name in res:
pro_id.append((pid))
print name
return {'domain':{'categ_temp2':[('id','in',pro_id)]}}
here i am using query which shows result like this in query analyzer,
4 phone
but in oboe method it shows in this way,
all product/phone
why it is getting all product all time how to trim it ?
One more thing domain is set with fields that woulds get data from particular table in which parent id ='1'
table have data in this way so that it would be more clear,
id(pk) parent id name
1 all product
2 1 phone
3 2 samsung
Hopes for your suggestion thanks in advance
I think you should see at the method name_get() of the product.category object. It is this method which computes the string displayed for name of product categories.

Categories