我試圖從我的資料框中提取一個值我有一列 ['Desc'] 它包含以下格式的句子
_000it_ZZZ$$$-
_0780it_ZBZT$$$-
_011it_BB$$$-
_000it_CCCC$$$-
我想提取 'it_' 和 '$$$' 之間的字串
我已經嘗試過這段代碼,但似乎不起作用
# initializing substrings
sub1 = "it_"
sub2 = "$$$"
# getting index of substrings
idx1 = df['DESC'].find(sub1)
idx2 = df['DESC'].find(sub2)
# length of substring 1 is added to
# get string from next character
df['results'] = df['DESC'][idx1 len(sub1) 1: idx2]
我會很感激你的幫助
uj5u.com熱心網友回復:
您可以使用str.extract在新列中獲得所需的輸出。
import pandas as pd
import re
df = pd.DataFrame({
'DESC' : ["_000it_ZZZ$$$-", "_0780it_ZBZT$$$-", "_011it_BB$$$-", "_000it_CCCC$$$-", "_000it_123$$$-"]
})
pat = r"(?<=it_)(. )(?=[\$]{3}-)"
df['results'] = df['DESC'].str.extract(pat)
print(df)
DESC results
0 _000it_ZZZ$$$- ZZZ
1 _0780it_ZBZT$$$- ZBZT
2 _011it_BB$$$- BB
3 _000it_CCCC$$$- CCCC
4 _000it_123$$$- 123
您可以在Regex101上查看正則運算式模式以獲取更多詳細資訊。
uj5u.com熱心網友回復:
您可以嘗試使用正則運算式模式。它與您在此處列出的案例相匹配,但我不能保證它會推廣到所有可能的模式。
import re
string = "_000it_ZZZ$$$-"
p = re.compile(r"(?<=it_)(.*)(?<!\W)")
m = p.findall(string)
print(m) # ['_ZZZ']
該模式在字串中查找it,然后停止,直到遇到非單詞字符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/525422.html
下一篇:使用函式就地改變多個熊貓資料框
