Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove "x" number of characters from a string in a pandas dataframe?

I have a pandas dataframe df looking like this:

a                 b
thisisastring     5
anotherstring     6
thirdstring       7

I want to remove characters from the left of the strings in column a based on the number in column b. So I tried:

df["a"] = d["a"].str[df["b"]:]

But this will result in:

a                 b
NaN               5
NaN               6
NaN               7

Instead of:

a                 b
sastring          5
rstring           6
ring              7

Any help? Thanks in advance!

like image 365
cian Avatar asked Dec 23 '22 03:12

cian


2 Answers

Using zip with string slice

df.a=[x[y:] for x,y in zip(df.a,df.b)]
df
Out[584]: 
          a  b
0  sastring  5
1   rstring  6
2      ring  7
like image 77
BENY Avatar answered Feb 09 '23 00:02

BENY


You can do it with apply, to apply this row-wise:

df.apply(lambda x: x.a[x.b:],axis=1)

0    sastring
1     rstring
2        ring
dtype: object
like image 39
sacuL Avatar answered Feb 08 '23 23:02

sacuL