简体   繁体   中英

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.

Use apply with indexing:

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

Or list comprehension with zip if no NaN s 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM