簡體   English   中英

Python-從逆中獲取特定字符后的字符串

[英]Python - get string after specific character from inverse

我正在嘗試捕獲這些電子郵件列表的域。 我在電子郵件中有子域,並試圖將其刪除。 我只需要在'之前和之后輸入一個字符串。 從后退

ids = [1,2,3,4,5,6,7,8]
emails = ['gmail.com','aol.com','','123.abc.edu','123.er.abc.edu','','abc.gov','test.net']
df = pd.DataFrame({'ids':ids,'emails':emails})
df

ids emails
0   1   gmail.com
1   2   aol.com
2   3   
3   4   123.abc.edu
4   5   123.er.abc.edu
5   6   
6   7   abc.gov
7   8   test.net

試過這個和-1、2:...等的組合

df.emails.str.split(".", 1).str[-1]

0           com
1           com
2              
3       abc.edu
4    er.abc.edu
5              
6           gov
7           net

需要這樣的輸出

ids emails
0   1   gmail.com
1   2   aol.com
2   3   
3   4   abc.edu
4   5   abc.edu
5   6   
6   7   abc.gov
7   8   test.net

通過將1作為第二個參數傳遞給split()可以將拆分限制為1。

改用:

df.emails.str.split(".").str[-2:]

獲取拆分字符串的最后兩段:

0    [gmail, com]
1      [aol, com]
2              []
3      [abc, edu]
4      [abc, edu]
5              []
6      [abc, gov]
7     [test, net]

要獲得包含點的字符串形式的輸出,請鏈接一個方法以連接上一個輸出:

In []: df.emails.str.split(".").str[-2:].str.join(".")
Out[]: 
0    gmail.com
1      aol.com
2             
3      abc.edu
4      abc.edu
5             
6      abc.gov
7     test.net
Name: emails, dtype: object

您可以預處理電子郵件列表

emails = ['gmail.com','aol.com','','123.abc.edu','123.er.abc.edu','','abc.gov','test.net']

emails_filtered = []
for email in emails:
    if '.' in email:
        emails_filtered.append( '.'.join( [ email.split('.')[:-2] ] ) )
    else:
        emails_filtered.append('')

df = pd.DataFrame({'ids':ids,'emails':emails_filtered})

希望能幫助到你。

嘗試這個

df.emails.str.split(".").str[-2:].str.join(sep='.')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM