0

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.

rakurakur
  • 33
  • 4
  • You are looking for `eval()`. But your whole approach sounds like you are doing something wrong. – Jonathan Scholbach Sep 13 '21 at 14:04
  • My understanding is that `ast.literal_eval()` is considered slightly more secure than `eval()` but yes, these seem like the best candidates given the task as written – G. Anderson Sep 13 '21 at 14:07
  • I know it's not ideal. I'm not supposed to hard code the sentence structure into python and something like this seems like it would be the best way to do it. If there is another way to do it I'm more than open to other ideas. – rakurakur Sep 13 '21 at 14:42

1 Answers1

2

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.