Slice series based on values in another series of the same data frame

if you’re on a recent version of pandas supporting nullale integers (Int64), then first cast collen to Int64. Then use that as for string slicing.

df.collen = df.collen.astype('Int64')

next, use the following lambda to generate the new column

df['new_col_str'] = df.apply(
    lambda x: x.colstr if pd.isnull(x.colstr) or pd.isnull(x.collen) else x.colstr[:x.collen], 
    axis=1
    )

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top