Getting substring based on another column in a pandas dataframe
<p>Hi is there a way to get a substring of a column based on another column?</p>

<pre><code>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
</code></pre>

<p>What i would expect is something like:</p>

<pre><code>for row in x.itertuples():
    print row[2][:row[1]]

be
bre
ber
</code></pre>

<p>where the result is the substring of name based on digit.</p>

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

<p>Appreciate any feedback.</p>

<p>Use <code>apply</code> with <code>axis=1</code> for row-wise with a <code>lambda</code> so you access each column for slicing:</p>

<pre><code>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
</code></pre>

python pandas dataframe