How to trim strings based on values from another column in pandas?

Viewed 70

I have a pandas data frame like below:

df:

col1       col2 
ACDCAAAAA    4
CDACAAA      2
ADDCAAAAA    3

I need to trim col1 strings based corresponding col2 values like below:

dfout:

col1     col2 
ACDCA      4
CDACA      2
ADDCAA     3

I tried : df['col1].str[:-(df['col2'])] but getting NaN in output.

Does anyone know how to do that? Thanks for your time.

3 Answers

Use list comprhension with zip:

df['new'] = [a[:-b] for a, b in zip(df['col1'], df['col2'])]

A regex option might be:

df["col1"] = df["col1"].str.replace(r'.{' + df["col2"].astype(str) + r'}$', '')

Use df.apply:

In [2613]: df['col1'] = df.apply(lambda x: x['col1'][: x['col2'] + 1], 1)
Related