Substring column in Pandas based another column

Viewed 53

I'm trying to substring a column based on the length of another column but the resultset is NaN. What am I doing wrong?

import pandas as pd 
df = pd.DataFrame([['abcdefghi','xyz'], ['abcdefghi', 'z']], columns=['col1', 'col2'])  

df.col1.str[:df.col2.str.len()] 

0   NaN
1   NaN
Name: col1, dtype: float64

Here is what I am expecting:

0   'abc'
1   'a'
3 Answers

I don't think string indexing would take a series. I would do a list comprehension:

df['extract'] = [r.col1[:len(r.col2)] for _,r in df.iterrows()]

Or

df['extract'] = [s1[:len(s2)] for s1,s2 in zip(df.col1, df.col2)]

Output:

        col1 col2 extract
0  abcdefghi  xyz     abc
1  abcdefghi    z       a

using numpy and converting the array to pd.Series

def slicer(start=None, stop=None, step=1):
    return np.vectorize(lambda x: x[start:stop:step], otypes=[str])


df["new_str"] = pd.Series(
    [slicer(0, i)(c) for i, c in zip(df["col2"].apply(len), df["col1"].values)]
)

print(df)

        col1 col2 new_str
0  abcdefghi  xyz     abc
1  abcdefghi    z       a

Here is a solution using lambda:

df['new'] = df.apply(lambda row: row['col1'][0:len(row['col2'])], axis=1)

Result:

        col1 col2  new
0  abcdefghi  xyz  abc
1  abcdefghi    z    a
Related