Pyd
Pyd

Reputation: 6159

How to slice a dataframe column based on another column

I have a df like this,

Main                        Length
Sri playnig well cricket    5
sri went out                2
Ram is in                   1 
Ram went to UK,US           2

I am trying to slice the df["Main"] based on df["Length"]

My expected output is,

Main                        Length
Sri p                       5
sr                          2
R                           1 
Ra                          2

I tried

def slicer(row):
    for i in df["Length"]:
        row['Main'].slice(0,i)
    return row

 df.apply(slicer,axis=1)

but I am getting, AttributeError: ("'str' object has no attribute 'slice'", 'occurred at index 0') please help.

Upvotes: 2

Views: 543

Answers (1)

jezrael
jezrael

Reputation: 862641

Use apply with indexing:

df['Main'] = df.apply(lambda x: x['Main'][:x['Length']], axis=1)

Or list comprehension with zip if no NaNs values:

df['Main'] = [a[:b] for a, b in zip(df['Main'], df['Length'])]

print(df)
    Main  Length
0  Sri p       5
1     sr       2
2      R       1
3     Ra       2

For more general solution is possible use if-else:

df['Main'] = [a[:b] if len(a) < b else a for a, b in zip(df['Main'], df['Length'])]
print(df)
                       Main  Length
0  Sri playnig well cricket     100
1              sri went out       2
2                 Ram is in       1
3         Ram went to UK,US       2

Upvotes: 3

Related Questions