【问题标题】:execute part of string as code pandas/python执行部分字符串作为代码 pandas/python
【发布时间】:2021-05-27 01:31:14
【问题描述】:

这是 pandas df 列中的示例字符串值:

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

我想提取从 '.format()' 开始的代码部分,并在字符串中输入如下所示的值:

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)

我想在 pandas df 列中这样提取和输出:

 'Had 20 patients in 2020-04'

我尝试在 '.' 处拆分字符串但不确定如何将后半部分转换为代码而不是将执行的字符串。

感谢任何帮助

【问题讨论】:

  • 你在哪里有 pandas df 列?我所看到的只是三个局部变量。请提供与您的问题相关的示例。
  • 字符串num_of_persons等是否引用局部变量?有超过三个吗?

标签: python python-3.x pandas string dataframe


【解决方案1】:
foo, bar = col.split(".")
exec(f"text  = '{foo}'.{bar}")

exec() 用于在字符串中运行代码。

【讨论】:

  • 在这种情况下,“文本”是否包含“{2} 中有 {0} {1}”。格式(num_of_persons,type_of_person,date)还是包含“2020 年有 20 名患者- 04' ?
  • 它包含格式化的字符串,之后您不能更改变量,无需调用 exec()
【解决方案2】:

试试apply

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 2011-06-02
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多