Skip to content Skip to sidebar Skip to footer

How To Slice Strings In A Column By Another Column In Pandas

df=pd.DataFrame({'A':['abcde','fghij','klmno','pqrst'], 'B':[1,2,3,4]}) I want to slice column A by column B eg: abcde[:1]=a, klmno[:3]=klm but two statements all failed: df['n

Solution 1:

You need axis=1 in the apply method to loop through rows:

df['new_column'] = df.apply(lambda r: r.A[:r.B], axis=1)
df#       A   B   new_column#0  abcde   1   a#1  fghij   2   fg#2  klmno   3   klm#3  pqrst   4   pqrs

A less idiomatic but usually faster solution is to use zip:

df['new_column'] = [A[:B] for A, B in zip(df.A, df.B)]
df#       A   B   new_column#0  abcde   1   a#1  fghij   2   fg#2  klmno   3   klm#3  pqrst   4   pqrs

%timeit df.apply(lambdar: r.A[:r.B], axis=1)
# 1000 loops, best of 3: 440 µs per loop

%timeit [A[:B] for A, B in zip(df.A, df.B)]
# 10000 loops, best of 3: 27.6 µs per loop

Solution 2:

By using zip.May this solution is helpful for you.

enter image description here

Post a Comment for "How To Slice Strings In A Column By Another Column In Pandas"