2017-10-17 23 views
-2

我有一堆像字符串:正則表達式分組串是否存在與否

Bought [email protected] ABCD 
Bought [email protected] 
Sold [email protected] ABCD 

我想創建ABCD的數據框的所有字符串。

因此所需的數據框應該這樣說:

ACBD 
NaN 
ABCD 

如何可以解析字符串出第一使用正則表達式?我試過(ABCD|)但是返回空白。

+0

你已經試過了什麼?如果你想使用正則表達式,你是否檢查了https://docs.python.org/3/library/re.html python的re文檔? – erhesto

+0

你可以使用'split'然後取最後一個元素 – chakri

+0

你可以使用'@ \ w + [\ t] +(\ w +)?'。如果沒有捕獲組,那麼你知道它是'NaN' – ctwheels

回答

1

作爲一個整體片段:

import pandas as pd, numpy as np 

string = """Bought [email protected] ABCD 
Bought [email protected] 
Sold [email protected] ABCD""" 

needle = 'ABCD' 

def search(line): 
    return needle if line.endswith(needle) else np.nan 

df = pd.DataFrame((search(line) for line in string.split("\n"))) 

print(df) 

這使得使用.endswith(),功能search()和列表理解,將使用lambda函數產生

 0 
0 ABCD 
1 NaN 
2 ABCD 

更短:

df = pd.DataFrame(map(lambda x: needle if x.endswith(needle) else np.nan, string.split("\n"))) 
print(df) 

對於更個性化的解決方案,您需要e對實際的輸入字符串進行實驗。