[英]Python - extract a text from string after the initial extraction of the number
我的小學校項目變得有點復雜,因此我正在尋求幫助。 我有一個數據來自 Col1 中的一些文本,我用來提取最大數值。 現在,我一直在嘗試使用提取的數字來提取它前后的任何字符(從空格用於前綴,直到空格用於后綴)。
這是我的代碼:
from numpy import floor, int64
from numpy.core import numeric
import pandas as pd
data = [['aaa', 10], ['nick12 text 1 a 1000a', 15], ['juli078 aq 199 299-01 aaa', 14]]
df = pd.DataFrame(data, columns = ['col1', 'col2'])
print(df.dtypes)
pat = (r'(\d+(?:\.\d+)?)')
df['Number'] = df['col1'].str.extractall(pat).astype(int).max(level=0)
df['Number'] = df['Number'].fillna(0)
df['Number'] = df['Number'].astype(int)
print(df.dtypes)
print(df)
我想添加另一列 NumberText 以便我的最終結果如下所示:
col1 col2 Number NumberText
0 aaa 10 0
1 nick12 text 1 a 1000a 15 1000 1000a
2 juli078 aq 199 299-01 aaa 14 299 299-01
你可以試試:
df['NumberText'] = df.apply(lambda x: ' '.join([word if str(x['Number']) in word else '' for word in x['col1'].split(' ')]).strip(), axis=1)
Output:
col1 col2 Number NumberText
0 aaa 10 0
1 nick12 text 1 a 1000a 15 1000 1000a
2 juli078 aq 199 299-01 aaa 14 299 299-01
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.