how to turn a list item (string type) into a module function in python 3.10 - python-3.x

I had a weird idea to grab a list item and call it as module function, here is what I'm trying to do:
if you used dir() on random module it would return a list of its attributes, and I want to grab a specific item which is, in this case, randint, then invoke it as a working function using a,b as arguments and become in this form randint(a, b)
that's what I tried:
from random import randint #to avoid the dot notation and make it simple
a = 10
b = 100
var = dir(random)
print(var)
# here is the result
#randint index is 55
print(var[55])
>>> randint
I couldn't find out the type of the function randint() so I can convert the list item to it and try the following:
something(var[55] + "(a, b)")
is there a way I can achieve what I'm trying to do?

you can use the exec command that can execute any string.
updated your code, the below answer should work
from random import randint #to avoid the dot notation and make it simple
a = 10
b = 100
var = dir(random)
print(var)
function_string = "random_number = " + var[55] + f"({a},{b})"
#note that index number can be changed based on python version
print(function_string)
exec(function_string)
print(random_number)

Related

Pandas groupby: coordinates of current group

Suppose I have a data frame
import pandas as pd
df = pd.DataFrame({'group':['A','A','B','B','C','C'],'score':[1,2,3,4,5,6]})
At first, say, I want to compute the groups' sums of scores. I usually do
def group_func(x):
d = {}
d['sum_scores'] = x['score'].sum()
return pd.Series(d)
df.groupby('group').apply(group_func).reset_index()
Now suppose I want to modify group_func but this modification requires that I know the group identity of the current input x. I tried x['group'] and x[group].iloc[0] within the function's definition and neither worked.
Is there a way for the function group_func(x) to know the defining coordinates of the current input x?
In this toy example, say, I just want to get:
pd.DataFrame({'group':['A','B','C'],'sum_scores':[3,7,11],'name_of_group':['A','B','C']})
where obviously the last column just repeats the first one. I'd like to know how to make this last column using a function like group_func(x). Like: as group_func processes the x that corresponds to group 'A' and generates the value 3 for sum_scores, how do I extract the current identity 'A' within the local scope of group_func?
Just add .name
def group_func(x):
d = {}
d['sum_scores'] = x['score'].sum()
d['group_name'] = x.name # d['group_name'] = x['group'].iloc[0]
return pd.Series(d)
df.groupby('group').apply(group_func)
Out[63]:
sum_scores group_name
group
A 3 A
B 7 B
C 11 C
Your code fix see about marked line adding ''

converting a python string to a variable

I have read almost every similar question but none of them seems to solve my current problem.
In my python code, I am importing a string from my bashrc and in the following, I am defining the same name as a variable to index my dictionary. Here is the simple example
obs = os.environ['obs']
>> obs = 'id_0123'
id_0123 = numpy.where(position1 == 456)
>> position1[id_0123] = 456
>> position2[id_0123] = 789
But of course, when I do positions[obs], it throws an error since it is a string rather than an index (numpy.int64). So I have tried to look for a solution to convert my string into a variable but all solution suggesting to either convert into a dictionary or something else and assign the string to an integer, But I can not do that since my string is dynamic and will constantly change. In the end, I am going to have about 50 variables and I need to check the current obs corresponding to which variable, so I could use it as indices to access the parameters.
Edit:
Position1 and Position 2 are just bumpy arrays, so depending on the output of os.environ (which is 'id_0123' in this particular case), they will print an array element. So I can not assign 'id_0123' another string or number since I am using that exact name as a variable.
The logic is that there are many different arrays, I want to use the output of os.environ as an input to access the element of these arrays.
If you wanted to use a dictionary instead, this would work.
obs = 'id_0123'
my_dict = {obs: 'Tester'}
print (my_dict [obs])
print (my_dict ['id_0123'])
You could use the fact that (almost) everything is a dictionary in Python to create storage container that you index with obs:
container = lambda:None
container.id_0123 = ...
...
print(positions[container.__dict__[obs]])
Alternatively, you can use globals() or locals() to achieve the desired behavior:
import numpy
import os
def environment_to_variable(environment_key='obs', variable_values=globals()):
# Get the name of the variable we want to reference from the bash environment
variable_name = os.environ[environment_key]
# Grab the variable value that matches the named variable from the environment. Variable you want to reference must be visible in the global namespace by default.
variable_value = variable_values[variable_name]
return variable_value
positions = [2, 3, 5, 7, 11, 13]
id_0123 = 2 # could use numpy.where here
id_0456 = 4
index = environment_to_variable(variable_values=locals())
print(positions[index])
If you place this in a file called a.py, you can observe the following:
$ obs="id_0123" python ./a.py
5
$ obs="id_0456" python ./a.py
11
This allows you to index the array differently at runtime, which is what it seems like your intention is.

Iteration over two list in Python

I'm trying to iterate over two list - I'm working on a tool which will fill a web form, I already have some nice selenium code but I have a problem with the loop which will get email and ID from excel file. So I got an error:
for DUNS_data, Email_data in EmailsAdressCore():
TypeError: 'DataFrame' object is not callable
I already tried to use ddof=1 but I don't know where should I add this...
import pandas as pd
import xlrd
EmailsAdressCore = pd.read_excel (r'C:\Users\M0099969\Desktop\VW\DUNSBase.xlsx', sheet_name='Arkusz1')
DUNS_data = EmailsAdressCore['DUNS'].values.tolist()
Email_data = EmailsAdressCore['email'].values.tolist()
for DUNS_data, Email_data in EmailsAdressCore():
print('DUNS: ' + DUNS_data + 'Email adress is:' + Email_data)
So I would like to be able to print these two columns next to each other, I need this code to fill the form over the loop.
EmailsAdressCore is not a function, so you cannot try to call it using (). And you already extracted DUNS_data and Email_data, so you should just iterate over that.
I think what you are looking for is:
for d1, d2 in zip(DUNS_data, Email_data):
print('DUNS: ' + d1 + 'Email adress is:' + d2)
So the only way to iterate over 2 and more list is:
import itertools
from itertools import zip_longest
CategoryCore = pd.read_excel, sheet_name='Arkusz1')
IssueDesc = CategoryCore['Issue:'].values.tolist()
Category = CategoryCore['Category'].values.tolist()
for (a,b) in itertools.zip_longest(IssueDesc, Category):
print(a,b)
I couldn't find any other way and this loop works pretty well

How to get the specific value from the data using python?

data = ['{"osc":{"version":"1.0"}}']
or
data = ['{"device":{"network":{"ipv4_dante":{"auto":"testing"}}}}']
From the code above, I only get random outputs, but I need to get the last value i.e "1.0" or "testing" and so on.
I always need to get the last value. How can I do it using python?
Dictionaries have no "last" element. Assuming your dictionary doesn't branch and you want the "deepest" element, this should work:
import json
data = ['{"device":{"network":{"ipv4_dante":{"auto":"testing"}}}}']
obj = json.loads(data[0])
while isinstance(obj, dict):
obj = obj[list(obj.keys())[0]]
print(obj)
This should work -
import ast
x = ast.literal_eval(data[0])
while(type(x)==dict):
key = x.keys()[0]
x = x.get(key)
print(x)

Covert input into list elements in python

I have an input in python that looks like this:
20.1
25.9
31.2
33.2
31.2
25.5
28.1
23.2
stop
It is a sequence of floating point numbers, each on a separate line. I wish to iterate over them or convert them into list to iterate, but I can't find the right way to do it.
So far I have tried this:
list = [float(n) for n in input().split('\n')]
but it only returns me the first value.
I wish to convert all values into a list and keep the integrity of them.
The input function only reads a single line. You need to call it multiple times and check for 'stop'.
import sys
mylist = []
for line in sys.stdin:
if line.startswith('stop'):
break
else:
mylist.append(float(line))
print(mylist)
itertools.dropwhile can do some of the work for you. Give it a function that returns a False value when the iteration should stop, plus a sequence, and you can do the work in a list comprension.
import sys
import itertools
def not_stop_condition(line):
"""Return True unless a line with 'stop' is seen"""
return not line.startswith('stop')
mylist = [float(line) for line in itertools.takewhile(
not_stop_condition, sys.stdin)]
print(mylist)
Small functions that just implement a simple expression like not_stop_condition can be placed in-line in a lambda. A lambda is just an anonymous function - its called with any number of parameters and returns whatever the expression evaluates to.
import sys
import itertools
mylist = [float(line) for line in itertools.takewhile(
lambda line: not line.startswith('stop'), sys.stdin)]
print(mylist)

Resources