In detail:
I need this formula to work.
string = str(z)+":1.0 "+str(z+1)+":0.0" where z is a variable with a value.
will I be able to input this formula into a dictionary value with a specific key. Like
dicto={'A': 'str(z)+":1.0 "+str(z+1)+":0.0"'}
so that when i see a key value 'A' I should be able to use that formula in the dictionary
As I read your question, you wanted something like this:
dicto = {'A': lambda x: "{0!s}:1.0 {1!s}:0.0".format(x, x + 1)}
dicto['A'](2) # '2:1.0 3:0.0'
Use lambda function:
d = { 'A': lambda z: str(z)+":1.0 "+str(z+1)+":0.0" }
d['A'](5)
# returns: '5:1.0 6:0.0'
Related
I'm trying to implement something like this:
def RR(x):
x['A'] = x['A'] +1
return x
def Locked(x):
x['A'] = x['A'] + 2
return x
func_mapper = {"RR": RR, "Locked": Locked}
df = pd.DataFrame({'A':[1,1], 'LookupVal':['RR','Locked'],'ID':[1,2]})
df= df.groupby("ID").apply(lambda x: func_mapper[x.LookupVal.first()](x))
Output for column A would be 2, 6
where x.LookupVal is a column of strings (it will have the same value within each groupby("ID")) that I want to pass as the key to the dictionary lookup.
Any suggestions how to implement this??
Thanks!
The first is not what you think it is. It is for timeseries data and it requires an offset parameter. I think you are mistaken with groupby first
You can use iloc[0] to get the first value:
slice_b.groupby("ID").apply(lambda x: func_mapper[x.LookupVal.iloc[0]](x))
I am trying to evaluate the following expression (exp). I'm trying to replace var[i] in exp by values[i] and evaluate the expression and would really appreciate some help. I have tried re.subs and replace however it isn't working.
exp='((2*3.14)/(550*12))*((R*F*L)/t)'
var=['R','F','L','t']
values=[1202,10.12,15.63,60]
It should output: ((23.14)/(55012))((120210.12*15.63)/60)= 3.016
You can use a f-string with named values and format it with a dict
exp = "((2*3.14)/(550*12))*(({R}*{F}*{L})/{t})"
var = ["R", "F", "L", "t"]
values = [1202, 10.12, 15.63, 60]
valdict = dict(zip(var, values))
print(valdict)
filled = exp.format(**valdict)
print(filled)
print(eval(filled))
Which produces
{'R': 1202, 'F': 10.12, 'L': 15.63, 't': 60}
((2*3.14)/(550*12))*((1202*10.12*15.63)/60)
3.0151464826666667
Of course if you are the one building the var/values, you should skip the two lists and build the valdict directly, which makes it a lot more readable.
And if you want to print only three decimal digits use
print(f"{eval(filled):.3f}")
Which prints 3.015 and not 3.016 as you request, but it should be the right value.
Cheers!
I assume the value for each var is at the same index in the values list
You can just replace a variable with the corresponding value in values list to the exp string
exp='((2*3.14)/(550*12))*((R*F*L)/t)'
var=['R','F','L','t']
values=[1202,10.12,15.63,60]
for i,j in zip(var, values):
exp = exp.replace(i, str(j))
Output:
>>exp
'((2*3.14)/(550*12))*((1202*10.12*15.63)/60)'
You can call eval function to evaluate the value.
>>eval(exp)
3.0151464826666667
If you have only such simple variable names (single letter), then the following will be enough:
expr = '((2*3.14)/(550*12))*((R*F*L)/t)'
var = ['R','F','L','t']
values = [1202,10.12,15.63,60]
for n,v in zip(var, values):
expr = expr.replace(n,str(v))
print(f'{expr} = {eval(expr):.5f}')
Set format specifier to the desired one or remove it.
If you have more complex variables names, try using sympy. Example:
import sympy
var = sympy.symbols('R F L t')
values = [1202,10.12,15.63,60]
expr = sympy.sympify('((2*3.14)/(550*12))*((R*F*L)/t)', evaluate=False)
with sympy.evaluate(False):
num_expr = expr.subs(zip(var, values))
print(f'{num_expr} = {num_expr.doit():.5f}')
Can't get rid of printed '*1/', but you can just remove it by hands:
...
print(f'{num_expr} = {num_expr.doit():.5f}'.replace('*1/','/'))
About
in a python code which i seen in this site
https://amaral.northwestern.edu/blog/function-wrapper-and-python-decorator
The code
def my_add(m1, p1=0):
output_dict = {}
output_dict['r1'] = m1+p1
return output_dic
def my_deduct(m1, p1=0):
output_dict = {}
output_dict['r1'] = m1-p1
return output_dic
My doubt is , the code
output_dict['r1'] = m1+p1
represents that m1+p1 is stored in output_dict variable array in r1 th key. but "r1" is neither initialized nor even declared before used as a key. wont python throw a error ? .
if r1 is a variable , is it static or has a scope in the program?
No, python would not throw an error ,rather then this it would automatically create a key in output_dict with value assigned to it
'r1' is just a string, no need to initialize or declare it.
And output_dict['r1'] = m1 + p1 means:
if 'r1' in output_dict:
# change output_dict['r1'] to m1 + p1
else:
# create a 'r1' key in output_dict,
# and assign value `m1 + p1` to it
"r1" is just a string literal, like "hello" or "hi", and what output_dict['r1'] = m1+p1 is doing is that it is creating a key r1 in output_dict, and then assigning m1+p1 to it, all in one expression
A simpler example might be
In [42]: dct = {}
In [43]: dct['a']='b'
In [44]: dct
Out[44]: {'a': 'b'}
In [45]: dct['c']='d'
In [46]: dct
Out[46]: {'a': 'b', 'c': 'd'}
Here you see that after instantiating dct dictionary, I assigned a key and value pair a,b and then c,d
I have a more different type of keys in dict (there is no need to type values too)
'PL-1/KK-1/FO-1'
'PL-1/KK-2/GH-3'
'PL-1/KK-2'
'PL-1/KK-1/FO-4'
And I need a condition
if exist (key.split('/')[2])
do something
return data
else:
do something
return data
Desired output:
In the first condition, all keys make entries except 'PL-1/KK-2'.
Is there in python something like 'exist'?
No, there is no 'exists' operator.
In your case you should just test slashes:
if key.count('/') >= 2:
# ...
If you need to have the components of the key, store and test the length:
components = key.split('/')
if len(components) >= 2:
# ...
def has_key(i_dict, i_filter):
return any(k for k in i_dict.iterkeys() if i_filter(k))
# be it a dict called my_dict
# you could call it like
has_key(my_dict, lambda x: x.count("/") == 2)
# or
has_key(my_dict, lambda x: len(x.split("/"))==2)
here's a little test
>>> my_dict = {"a":1,"c":3}
>>> has_key(my_dict, lambda k:k=="a")
True
>>> has_key(my_dict, lambda k:k=="c")
True
>>> has_key(my_dict, lambda k:k=="x")
False
When attempting to histogram a list of numbers(in str formats) all of my numbers get broken up
for instance
a = ['1','1.5','2.5']
after running my histogram function
my dictionary looks like
{'1': 2, '2': 1, '5': 2, '.': 2}
my histogram function is
def histogram(a):
d = dict()
for c in a:
d[c] = d.get(c,0)+1
return d
I'm doing a project for school and have everything coded in, but when I get to doing the mode portion and I use numbers that aren't specifically int I get the above returns
How can I adjust/change this so it accepts the strings exactly as typed
Python 2.7 on Windows 7x64
You can convert each string element to a float before passing it your histogram function.
a = ['1','1.5','2.5']
a = [float(i) for i in a]
def histogram(a):
d = dict()
for c in a:
d[c] = d.get(c,0)+1
return d
print histogram(a)
There might be an error in your list definition. Running your code I get
{'1': 1, '1.5': 1, '2.5': 1}
If I change the definition of a from
a = ['1','1.5','2.5']
to
a = '1' '1.5' '2.5'
I get the output you showed us.
So please double check how your list is defined.
You can use something like this:
>>> a = ['1','1.5','2.5']
>>> dict.fromkeys(a, 0)
{'1': 0, '1.5': 0, '2.5': 0}
Now you can iterate over keys to set the corresponding value.
I have used the following dict comprehension to reduce my work.
>>> {key: float(key)+1 for key in a}
{'1': 2.0, '1.5': 2.5, '2.5': 3.5}
enjoy :)
The histgram function does work as it's written. If however you you inadvertently .join() your list your histogram with then histogram the resulting object. For instance... t = ['1.0','2.0','2.5'] and
s = s.join(t) s will then be == '1.02.02.5' and histogram(s) will count the decimals as values in the slice. My problem was that I had placed a .join() prior to calling histogram.
My appologies to anyone that wasted any real time on this.