user9185511
user9185511

Reputation: 814

Pandas - slicing column values based on another column

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

Upvotes: 1

Views: 1867

Answers (2)

Tacratis
Tacratis

Reputation: 1055

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.

Upvotes: 4

BENY
BENY

Reputation: 323226

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

Upvotes: 3

Related Questions