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

Time:04-04

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.

CodePudding user response:

Use list comprhension with zip:

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

CodePudding user response:

A regex option might be:

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

CodePudding user response:

Use df.apply:

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