0

This is the sample string value in a pandas df column :

'Had {0} {1} in {2}.format(num_of_persons,type_of_person,date)'

I want to extract the code part starting at '.format()' and input the values in the string where it would look something like this:

num_of_persons='20'
type_of_person ='patients'
date='2020-04'

text='Had {0} {1} in {2}'.format(num_of_persons,type_of_person,date)

I want to extract and output like this in the pandas df column :

 'Had 20 patients in 2020-04'

I tried splitting the string at '.' but unsure how to convert the second half into code and not the string that will execute.

Any help is appreciated

2
  • 1
    Where do you have a pandas df column? All I see is three local variables. Please make examples relevant to your problem. Commented May 27, 2021 at 1:45
  • do the strings num_of_persons etc refer to local variables? are there more than three? Commented May 27, 2021 at 2:30

2 Answers 2

3
foo, bar = col.split(".")
exec(f"text  = '{foo}'.{bar}")

exec() is used for running code in a string.

Sign up to request clarification or add additional context in comments.

2 Comments

Does 'text' in this case then contain 'Had {0} {1} in {2}'.format(num_of_persons,type_of_person,date) or would it contain 'Had 20 patients in 2020-04' ?
It contains the formatted String, you cannont change the variables after that, without recalling exec()
0

Try with apply

df['out'] = df.apply(lambda x : 'Had {0} {1} in {2}'.format(x['c1'],x['c2'],x['c3']),axis=1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.