如何在Pandas中将DataFrame两列拼接为指定格式的多行字符串?
如何将Pandas DataFrame列拼接为特定格式的多行字符串?
你的目标是将DataFrame的每行数据转换为指定格式的多行字符串,首先明确你的输入DataFrame:
import pandas as pd df = pd.DataFrame([[1,"This is the desc of id 1"],[4,"This is the desc of id 2"]], columns=["id","desc"])
你之前的代码无效是因为直接在f-string中引用df['id']会代入整个Series对象,而非每行的单个值。以下是两种可行的实现方式:
方法一:自定义函数+apply逐行处理
定义一个格式化每行的函数,再通过apply逐行应用:
def format_requirement(row): return f"""functionalRequirement {row['id']}{{ id: {row['id']} text: {row['desc']} risk: high verifymethod: test }}""" # 生成结果列 df['res'] = df.apply(format_requirement, axis=1)
方法二:lambda表达式简化写法
如果不需要复用格式化逻辑,可以用lambda表达式直接写在apply里:
df['res'] = df.apply( lambda x: f"functionalRequirement {x['id']}{{\n id: {x['id']}\n text: {x['desc']}\n risk: high\n verifymethod: test\n}}", axis=1 )
执行后,df['res']列的每个元素就是你需要的多行字符串,比如第一行的结果为:
functionalRequirement 1{ id: 1 text: This is the desc of id 1 risk: high verifymethod: test }
内容的提问来源于stack exchange,提问作者Selva
相关产品推荐
相关产品推荐

