1

How can I slice column values based on first & last character location indicators from two other columns?

Here is the code for a sample df:

import pandas as pd

d = {'W': ['abcde','abcde','abcde','abcde']}
df = pd.DataFrame(data=d)

df['First']=[0,0,0,0]
df['Last']=[1,2,3,5]
df['Slice']=['a','ab','abc','abcde']

print(df.head())   

Code output:

enter image description here

Desired Output:

enter image description here

2 Answers 2

4

I am not sure if this will be faster, but a similar approach would be:

df['Slice'] = df.apply(lambda x: x[0][x[1]:x[2]],axis=1)

Briefly, you go through each row (axis=1) and apply a custom function. The function takes the row (stored as x), and slices the first element using the second and third elements as indices for the slicing (that's the lambda part). I will be happy to elaborate more if this isn't clear.

Sign up to request clarification or add additional context in comments.

Comments

3

Just do it with for loop , you may worry about the speed , please check For loops with pandas - When should I care?

df['Slice']=[x[y:z]for x,y,z in zip(df.W,df.First,df.Last)]
df
Out[918]: 
       W  First  Last  Slice
0  abcde      0     1      a
1  abcde      0     2     ab
2  abcde      0     3    abc
3  abcde      0     5  abcde

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.