如何根据 pd.DataFrame 值创建 f 字符串列表(类似)?
How to create list of f-string (alike) based on pd.DataFrame values?
问题
如何根据 pandas DataFrame 的值创建带有占位符(即 "f-string"-like)的字符串列表?
例子
假设我有以下数据框:
import pandas as pd
data = [
['Alice', 13, 'apples'],
['Bob', 17, 'bananas']
]
df = pd.DataFrame(
data,
columns=['name', 'qty', 'fruit']
)
如何使用类似 f"{name} ate {qty} {fruit}"
的模式创建字符串列表?
换句话说,如何创建以下列表:
[
'Alice ate 13 apples',
'Bob ate 17 bananas'
]
将列表理解与字典列表结合使用
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']
或者:
a = [f"{name} ate {qty} {fruit}" for name, qty, fruit in df[['name','qty','fruit']].values]
使用
df.apply(lambda x: x['name'] + " ate " + str(x['qty']) + " " + x['fruit'],1).values
把这个作为答案,我们可以合并列并在最后调用 .tolist()
:
(df.name+' ate '+df.qty.astype(str)+' '+df.fruit).tolist()
输出:
['Alice ate 13 apples', 'Bob ate 17 bananas']
问题
如何根据 pandas DataFrame 的值创建带有占位符(即 "f-string"-like)的字符串列表?
例子
假设我有以下数据框:
import pandas as pd
data = [
['Alice', 13, 'apples'],
['Bob', 17, 'bananas']
]
df = pd.DataFrame(
data,
columns=['name', 'qty', 'fruit']
)
如何使用类似 f"{name} ate {qty} {fruit}"
的模式创建字符串列表?
换句话说,如何创建以下列表:
[
'Alice ate 13 apples',
'Bob ate 17 bananas'
]
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']
或者:
a = [f"{name} ate {qty} {fruit}" for name, qty, fruit in df[['name','qty','fruit']].values]
使用
df.apply(lambda x: x['name'] + " ate " + str(x['qty']) + " " + x['fruit'],1).values
把这个作为答案,我们可以合并列并在最后调用 .tolist()
:
(df.name+' ate '+df.qty.astype(str)+' '+df.fruit).tolist()
输出:
['Alice ate 13 apples', 'Bob ate 17 bananas']