簡體   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