1

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?

anix-anirban
  • 85
  • 1
  • 1
  • 8

1 Answers1

1

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
piterbarg
  • 8,089
  • 2
  • 6
  • 22
  • Thanks, it almost works for me when the values are integer. What will be the modification when values are string, say, 'Red' and 'Green'? – anix-anirban Dec 01 '20 at 12:06
  • @anix-anirban I added string example in the answer – piterbarg Dec 01 '20 at 12:14
  • @anix-anirban glad it helped! But do not overuse `exec`as it is generally considered bad practice, see [here](https://stackoverflow.com/questions/21553641/python-is-exec-always-bad-practice-and-if-so-why-not-deprecated#:~:text=As%20explained%20in%20other%20questions,issues%20and%20generally%20bad%20programming.). You can access those values in `df` using standard dtaframe methods so perhaps worth thinking about your design a bit more. – piterbarg Dec 01 '20 at 12:36