Skip to content Skip to sidebar Skip to footer

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': ['abc

Solution 1:

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  FirstLast  Slice
0  abcde      01      a
1  abcde      02     ab
2  abcde      03    abc
3  abcde      05  abcde

Solution 2:

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

df['Slice'] = df.apply(lambdax: 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.

Post a Comment for "Pandas - Slicing Column Values Based On Another Column"