Pandas: 如何将两列连接为多行字符串?

huangapple go评论58阅读模式
英文:

Pandas: How can I concatenate 2 columns as a multiline string?

问题

我有一个pandas数据框想要使用多行字符串来连接它们以下是我的pandas数据框
```python
pd.DataFrame([[1,"This is the desc of id 1"],[4,"This is the desc of id 2"]], columns=["id","desc"])

我想要的字符串如下,

functionalRequirement 1{{
  id: 1
  text: This is the desc of id 1
  risk: high
  verifymethod: test
}}

我尝试了下面的代码,但它没有工作。

df['res'] = f"""
functionalRequirement {df['id']} {{
    id: {df['id']}
    text: {df['desc']}
    risk: high
    verifymethod: test
}} 
"""

我该如何做?


<details>
<summary>英文:</summary>

I have a pandas dataframe and I want to concatenate them using multiline string. Below is my pandas dataframe,
```{python}
pd.DataFrame([[1,&quot;This is the desc of id 1&quot;],[4,&quot;This is the desc of id 2&quot;]], columns=[&quot;id&quot;,&quot;desc&quot;])

I wanted string like below,

functionalRequirement 1{{
  id: 1
  text: This is the desc of id 1
  risk: high
  verifymethod: test
}}

I tried below code but it didnt work.

df[&#39;res&#39;] = f&quot;&quot;&quot;
functionaRequirement {df[&#39;id&#39;]} {{
    id: {df[&#39;id&#39;]}
    text: {df[&#39;desc&#39;]}
    risk: high
    verifymethod: test
}} 
&quot;&quot;&quot;

How can I do it?

答案1

得分: 2

Sure, here is the translated code portion:

fstring = &quot;&quot;&quot;functionaRequirement {id} {{
     id: {id}
     text: {desc}
     risk: high
     verifymethod: test
 }}&quot;&quot;&quot;

df[&quot;res&quot;] = df.apply(lambda r: fstring.format(id=r.id, desc=r.desc), axis=1)

&gt;&gt;&gt; print(df.res[0])
functionaRequirement 1 {{
    id: 1
    text: 这是id 1的描述
    risk: high
    verifymethod: test
}}

Please note that I have translated the text "This is the desc of id 1" to "这是id 1的描述" in the output.

英文:

Use string formatting and apply it over all rows


fstring = &quot;&quot;&quot;functionaRequirement {id} {{
     id: {id}
     text: {desc}
     risk: high
     verifymethod: test
 }}&quot;&quot;&quot;

df[&quot;res&quot;] = df.apply(lambda r: fstring.format(id=r.id, desc=r.desc), axis=1)

&gt;&gt;&gt; print(df.res[0])
functionaRequirement 1 {
    id: 1
    text: This is the desc of id 1
    risk: high
    verifymethod: test
}

答案2

得分: 1

你可以使用列表推导式:

df['res'] = [f"""
functionaRequirement {id} {{
    id: {id}
    text: {desc}
    risk: high
    verifymethod: test
}} 
""" for id, desc in zip(df['id'], df['desc'])]

或者如果性能很重要:

ID = df['id'].astype(str)
df['res'] = '\nfunctionaRequirement '+ID+' {\n    id: '+ID+'\n    text: '+df['desc']+'\n    risk: high\n    verifymethod: test\n}'

输出:

   id                      desc                                                                                                                      res
0   1  This is the desc of id 1  \nfunctionaRequirement 1 {\n    id: 1\n    text: This is the desc of id 1\n    risk: high\n    verifymethod: test\n} 
1   4  This is the desc of id 2  \nfunctionaRequirement 4 {\n    id: 4\n    text: This is the desc of id 2\n    risk: high\n    verifymethod: test\n} 
英文:

You could use a list comprehension:

df[&#39;res&#39;] = [f&quot;&quot;&quot;
functionaRequirement {id} {{
    id: {id}
    text: {desc}
    risk: high
    verifymethod: test
}} 
&quot;&quot;&quot; for id, desc in zip(df[&#39;id&#39;], df[&#39;desc&#39;])]

Or if performance matters:

ID = df[&#39;id&#39;].astype(str)
df[&#39;res&#39;] = &#39;\nfunctionaRequirement &#39;+ID+&#39; {\n    id: &#39;+ID+&#39;\n    text: &#39;+df[&#39;desc&#39;]+&#39;\n    risk: high\n    verifymethod: test\n}&#39;

Output:

   id                      desc                                                                                                                      res
0   1  This is the desc of id 1  \nfunctionaRequirement 1 {\n    id: 1\n    text: This is the desc of id 1\n    risk: high\n    verifymethod: test\n} \n
1   4  This is the desc of id 2  \nfunctionaRequirement 4 {\n    id: 4\n    text: This is the desc of id 2\n    risk: high\n    verifymethod: test\n} \n

答案3

得分: 0

你可以使用 string 模板与 to_dict 导出你的数据框作为字典:

import string

TEMPLATE = string.Template("""\
functionaRequirement ${id} {{
    id: ${id}
    text: ${desc}
    risk: high
    verifymethod: test
}}""")

df['res'] = list(map(TEMPLATE.substitute, df.to_dict('records')))
# 或者
df['res'] = [TEMPLATE.substitute(rec) for rec in df.to_dict('records')]

输出:

>>> df
   id                      desc                                                res
0   1  This is the desc of id 1  functionaRequirement 1 {{
    id: 1
    text: This is the desc of id 1
    risk: high
    verifymethod: test
}}
1   4  This is the desc of id 2  functionaRequirement 4 {{
    id: 4
    text: This is the desc of id 2
    risk: high
    verifymethod: test
}}

>>> print(df.loc[0, 'res'])
functionaRequirement 1 {{
    id: 1
    text: This is the desc of id 1
    risk: high
    verifymethod: test
}}
英文:

You can use string template withT to_dict to export your dataframe as dict:

import string

TEMPLATE = string.Template(&quot;&quot;&quot;\
functionaRequirement ${id} {{
    id: ${id}
    text: ${desc}
    risk: high
    verifymethod: test
}}&quot;&quot;&quot;)

df[&#39;res&#39;] = list(map(TEMPLATE.substitute, df.to_dict(&#39;records&#39;)))
# OR
df[&#39;res&#39;] = [TEMPLATE.substitute(rec) for rec in df.to_dict(&#39;records&#39;)]

Output:

&gt;&gt;&gt; df
   id                      desc                                                res
0   1  This is the desc of id 1  functionaRequirement 1 {{\n    id: 1\n    text...
1   4  This is the desc of id 2  functionaRequirement 4 {{\n    id: 4\n    text...

&gt;&gt;&gt; print(df.loc[0, &#39;res&#39;])
functionaRequirement 1 {{
    id: 1
    text: This is the desc of id 1
    risk: high
    verifymethod: test
}}

huangapple
  • 本文由 发表于 2023年7月6日 18:14:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76627765.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定