S.Nicko S.Nicko - 3 months ago 11
Python Question

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?

Answer

Please try this:

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