5

Hi is there a way to get a substring of a column based on another column?

import pandas as pd
x = pd.DataFrame({'name':['bernard','brenden','bern'],'digit':[2,3,3]})
x

     digit  name
0   2   bernard
1   3   brenden
2   3   bern

What i would expect is something like:

for row in x.itertuples():
    print row[2][:row[1]]

be
bre
ber

where the result is the substring of name based on digit.

I know if I really want to I can create a list based on the itertuples function but does not seem right and also, I always try to create a vectorized method.

Appreciate any feedback.

1 Answer 1

10

Use apply with axis=1 for row-wise with a lambda so you access each column for slicing:

In [68]:
x = pd.DataFrame({'name':['bernard','brenden','bern'],'digit':[2,3,3]})
x.apply(lambda x: x['name'][:x['digit']], axis=1)

Out[68]:
0     be
1    bre
2    ber
dtype: object
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.