![](/img/trans.png)
[英]How to extract strings from a list in a column in a python pandas dataframe?
[英]Python: How to extract multiple strings from pandas dataframe column
我有一個包含以下格式字符串的特定列的數據集:Building = Building_A and Floor = Floor_4 Building = Building_D and Floor = Floor_2
我只想提取建築物和樓層名稱,並連接成一個字符串/新列。 例如 Building_A/Floor_4 Building_D/Floor_2
我花了大約一個小時瀏覽以前的帖子,但找不到與我正在嘗試做的事情相匹配的內容。 任何幫助,將不勝感激。
假設我們有數據幀df
:
import pandas as pd
df = pd.DataFrame({'txt': ["Building = Building_A and Floor = Floor_4",\
"Building = Building_Z and Floor = Floor_9",\
"Building = Martello and Floor = Ground"]})
首先定義要提取的模式:
pat = "(Floor_\d+)|(Building_\w{1})"
或者,如果您查找"= "
之后的所有單詞:
pat = r"(?<== )(\w+)"
請注意模式定義中的后視(?<=)
。
然后將 lambda 函數應用於列txt
:
df['txt_extract'] = \
df[['txt']].apply(lambda r: "/".join(r.str.extractall(pat).stack()), axis=1)
結果:
0 Building_A/Floor_4
1 Building_Z/Floor_9
2 Martello/Ground
代替str.extract
使用str.extractall
查找所有出現的模式。 結果搜索堆疊並使用"/"
分隔符連接。 請注意,找到的模式的順序被保留,這對您的情況可能很重要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.