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.