Apply function to create string with multiple columns as argument

2024/11/18 20:32:47

I have a dataframe like this:

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

I want to create a new column with a sentence, like this:

    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)

It would be something like this:

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 stringdf['sentence']=df[['name','size','type','av_size_type']].apply(func)

However, apparently this sort of synthax doesn't work.

Would anyone have a suggestion for that?

Answer

Use a splat and unpack

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...

If you want, you can use dictionary unpacking

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...
https://en.xdnf.cn/q/71017.html

Related Q&A

Popping items from a list using a loop in Python [duplicate]

This question already has answers here:Strange result when removing item from a list while iterating over it in Python(12 answers)Closed 3 months ago.Im trying to write a for loop in python to pop out …

Django Admin Media prefix URL issue

i ve the following folder structuresrc\BAT\templates\admin\base.html src\BAT\media\base.css src\BAT\media\admin-media\base.csssettings.pyMEDIA_ROOT = os.path.join( APP_DIR, media ) MEDIA_URL = /media/ …

lazy processpoolexecutor in Python?

I have a large number of tasks that I want to execute and make the results available via a generator. However, using a ProcessPoolExecutor and as_completed will evaluate the results greedily and store …

error occurs when installing cryptography for scrapy in virtualenv on OS X [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Can Python do DI seamlessly without relying on a service locator?

Im coming from the C# world, so my views may be a little skewed. Im looking to do DI in Python, however Im noticing a trend with libraries where they all appear to rely on a service locator. That is, y…

Producing pdf report from python with bullet points

I would like to produce a dynamic pdf document from a python script that looks like the image below. Each sentence starts with a bullet point, and the text and number of lines depends on what the user …

Converting bits to bytes in Python

I am trying to convert a bit string into a byte string, in Python 3.x. In each byte, bits are filled from high order to low order. The last byte is filled with zeros if necessary. The bit string is ini…

Install python package from private pypiserver

I have setup a pypiserver behind an nginx proxy which uses htpasswd for authentication. I am currently able to upload sdists, but I cant figure out how to download them. I want to be able to download t…

Matplotlib Table- Assign different text alignments to different columns

I am creating a two column table and want the text to be as close as possible. How can I specify that the first column be right aligned and the second be left aligned?Ive tried by setting the general …

How would I make a random hexdigit code generator using .join and for loops?

I am new to programming and one assignment I have to do is create a random hexdigit colour code generator using for loops and .join. Is my program below even close to how you do it, or is it completely…