繁体   English   中英

如何基于另一列对数据框列进行切片

[英]How to slice a dataframe column based on another column

我有这样的df

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

我正在尝试df["Main"] based on df["Length"]切割df["Main"] based on df["Length"]

我的预期输出是

Main                        Length
Sri p                       5
sr                          2
R                           1 
Ra                          2

我试过了

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

 df.apply(slicer,axis=1)

但是我得到了AttributeError: ("'str' object has no attribute 'slice'", 'occurred at index 0')请帮忙。

使用apply与索引:

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

如果没有NaN值,请使用zip列出理解:

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

对于更通用的解决方案,可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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