如何基于 pd.DataFrame 值创建 f-string(类似)列表?

ebo*_*osi 2 python dataframe pandas f-string

问题
如何根据pandas DataFrame 的值创建带有占位符(即“f-string”之类的)的字符串列表?

例子

想象一下我有以下数据框:

import pandas as pd

data = [
    ['Alice', 13, 'apples'],
    ['Bob', 17, 'bananas']
]

df = pd.DataFrame(
    data,
    columns=['name', 'qty', 'fruit']
)
Run Code Online (Sandbox Code Playgroud)

如何使用类似f"{name} ate {qty} {fruit}"模式创建字符串列表?
换句话说,如何创建以下列表:

[
    'Alice ate 13 apples',
    'Bob ate 17 bananas'
]
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 6

将列表理解与 dicts 列表结合使用DataFrame.to_dict

a = [f"{x['name']} ate {x['qty']} {x['fruit']}" for x in df.to_dict('r')]
print (a)
['Alice ate 13 apples', 'Bob ate 17 bananas']
Run Code Online (Sandbox Code Playgroud)

或者:

a = [f"{name} ate {qty} {fruit}" for name, qty, fruit in df[['name','qty','fruit']].values]
Run Code Online (Sandbox Code Playgroud)