gpt4 book ai didi

python - 应用函数创建多列作为参数的字符串

转载 作者:行者123 更新时间:2023-11-28 20:01:54 24 4
gpt4 key购买 nike

我有一个这样的数据框:

     name .  size . type    .  av_size_type
0 John . 23 . Qapra' . 22
1 Dan . 21 . nuk'neH . 12
2 Monica . 12 . kahless . 15

我想用一句话创建一个新的专栏,像这样:

    name .  size . type    .  av_size_type  .   sentence
0 John . 23 . Qapra' . 22 . "John has size 23, above the average of Qapra' type (22)"
1 Dan . 21 . nuk'neH . 12 . "Dan has size 21, above the average of nuk'neH type (21)"
2 Monica . 12 . kahless . 15 . "Monica has size 12l, above the average of kahless type (12)

应该是这样的:

def func(x):
string="{0} has size {1}, above the average of {2} type ({3})".format(x[0],x[1],x[2],x[3])
return string

df['sentence']=df[['name','size','type','av_size_type']].apply(func)

但是,显然这种合成器不起作用。

有人对此有什么建议吗?

最佳答案

使用 splat 并解压

string = lambda x: "{} has size {}, above the average of {} type ({})".format(*x)

df.assign(sentence=df.apply(string, 1))

name size type av_size_type sentence
0 John 23 Qapra' 22 John has size 23, above the average of Qapra' ...
1 Dan 21 nuk'neH 12 Dan has size 21, above the average of nuk'neH ...
2 Monica 12 kahless 15 Monica has size 12, above the average of kahle...

如果你愿意,你可以使用字典解包

string = lambda x: "{name} has size {size}, above the average of {type} type ({av_size_type})".format(**x)

df.assign(sentence=df.apply(string, 1))

name size type av_size_type sentence
0 John 23 Qapra' 22 John has size 23, above the average of Qapra' ...
1 Dan 21 nuk'neH 12 Dan has size 21, above the average of nuk'neH ...
2 Monica 12 kahless 15 Monica has size 12, above the average of kahle...

关于python - 应用函数创建多列作为参数的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49122917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com