![](/img/trans.png)
[英]Remove the rows from pandas dataframe, that has sentences longer than certain word length
[英]Remove the row from dataframe, that has string length greater than a certain number, after a certain character(“,”) till end
輸入:我有一個名稱包含 2 個值除以“,”的數據框
id name
1 xy,ab
2 cv,asdf
3 piy,bs
預期輸出:我想刪除“,”后名稱字符串長度大於 2 的行。
id name
1 xy,ab
3 piy,bs
我試過的代碼:
df = df[~df['name'].str.split().str.len().ge(2)]
df
此代碼僅刪除大於 2 的字符串長度,但我希望它發生在“,”之后。
您可以使用Series.str.match
並傳遞regex
:
>>> df[df['name'].str.match('.*?,\w{0,2}$')]
id name
0 1 xy,ab
2 3 piy,bs
或者你可以用逗號分割值,取最后一個值,然后檢查長度是否小於或等於 2:
>>> df[df['name'].str.split(',').str[-1].str.len().le(2)]
id name
0 1 xy,ab
2 3 piy,bs
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.