P.Dove
P.Dove

Reputation: 89

Make a new column of the first n letters of a column, where n is the value in another column

I have a dataframe with names and ages:

name:  age: 
john    2
sean    3
jack    1
peter   4 

Depending on their age n I want to print the first n letters of their name, so for instance sean becomes sea in a new column.

I have tried this:

family['newcol'] = [x[:y] for x in family['name'] and for y in family['age']]

but it hasn't worked. Can anyone please give me a solution?

Upvotes: 1

Views: 75

Answers (1)

milos.ai
milos.ai

Reputation: 3930

Please try this:

family['newcol'] = [family.ix[x]['name'][0:family.ix[x]['age']] for x in family.index]

Upvotes: 2

Related Questions