Can I write a line of code in an excel cell and then import it into python?

I write a line of code in an excel cell. I import it it as a df into python. It has 1 call df[‘column’]. It treats it as a string and doesn’t call from the column I’m looking for. I want the string to ‘activate’ when I merge the imported df to a new df.

Imported df has cells with something like… ‘This is part of the’ + df[‘adjective’] + ‘ string I want imported.’ So it is written as a code, I just want it to act as a code.

The original df has a column, ‘adjective’. When I merge it to the new dataframe I want the string to adapt to the new dataframe. But the whole cell is treated as one long string. Is there a way to get the string to act like a code a I wrote in python?

I know there are other, more roundabout, ways to get my sentence to work. I’ve got it to work with .replace but that’s not as flexible as I would like.

df1 = pd. DataFrame({'adjective': ['small','Big'], 'key': [1,2]})  
imported_df = pd.DataFrame({'key':[1,2], 'sentence': ['random words' + df2['adjective'] + 'problem', 'other random string' + df2['adjective'] + 'random words']})  

df2 = df1.merge(imported_df[['key]])

I’m getting this string, ‘random words’ + df1[‘adjective’] + ‘problem’.

I want ‘random words small problem’ or ‘other random string Big random words’. But it’s not reading the call for df1[‘adjective’]. It is leaving that in the string.

Answer

You can use the openpyxl package to read the excel specific cells, or if the codes are more organized you can use pandas read_excel() to read the codes as a string or a series of strings, then, you can use the solutions proposed in the topic here to run the codes.

I firmly advise using try and except to run the codes and debug each code if there is any bug.