Home > other >  Create column parsing values from same row
Create column parsing values from same row

Time:05-17

I have the following dataset:

import pandas as pd
dataset = { 'name': ['Clovis', 'Priscila', 'Raul', 'Alice'], 'age': [28, 35, 4, 11] }
family = pd.DataFrame(dataset)

I need a new column with the text: "Clovis is 28 years old", but obviously for every row

I try using .eval() and .assign(), but I don't get the expected result enter image description here

CodePudding user response:

This will add a new column 'text':

family['text'] = family.apply(lambda x: "{} is {} year old".format(x['name'], x['age']), axis=1)

using apply and format

CodePudding user response:

The faster is likely to use a list comprehension.

For 2 columns:

family['quote'] = [f'{name} is {age} years old' for name, age in
                   zip(family['name'], family['age'])]

generalization to an arbitrary number of columns (the number should match the number of {} in the string):

cols = ['name', 'age']
family['quote'] = ['{} is {} years old'.format(*x)
                   for _,x in family[cols].iterrows()]

output:

       name  age                     quote
0    Clovis   28    Clovis is 28 years old
1  Priscila   35  Priscila is 35 years old
2      Raul    4       Raul is 4 years old
3     Alice   11     Alice is 11 years old

CodePudding user response:

your dataset column name's must change and like this

dataset = { 'First': ['Clovis', 'Priscila', 'Raul', 'Alice'], 'age': [28, 35, 4, 11] }
family = pd.DataFrame(dataset)

create a function for new column

def create_string(name:str,age:int):
    return f"{name} is {age} years old"

using this method with apply

family["new_column"]=family.apply(lambda row: create_string(row.First,row.age),axis=1)

the result

enter image description here

  • Related