I have a pandas dataframe as follows:
a = pd.DataFrame({'col1': ('x','y'), 'col2':(1,2)})
I want to extract variable and associated values, such as,
x=1
y=2
How can I do that?
I have a pandas dataframe as follows:
a = pd.DataFrame({'col1': ('x','y'), 'col2':(1,2)})
I want to extract variable and associated values, such as,
x=1
y=2
How can I do that?
You can use exec
to parse and execute Python code written in a string.
As an example exec('x=1')
will create and instantiate variable x
that you can use later in your code.
With this in mind the following will work
s = ','.join(a['col1']) + '=' + ','.join(a['col2'].astype('str'))
exec(s)
print(x,y)
produces
1 2
Here s
is given as a string 'x,y=1,2'
If the values are say strings, you need to insert quote marks. Basically s
needs to look like valid Python code. So for example you can do
a = pd.DataFrame({'col1': ('x','y'), 'col2':('red','green')})
s = ','.join(a['col1']) + '=' + ','.join(a['col2'].apply(lambda s:f'\'{s}\''))
exec(s)
print(x,y)
produces
red green