Python - 在初始提取数字后从字符串中提取文本
Python - extract a text from string after the initial extraction of the number
我的小学校项目有点复杂,因此我正在寻求帮助。我有一个数据来自 Col1 中的一些文本,我用它来提取最大数值。现在,我一直在尝试使用提取的数字来提取它前后的任何字符(从 space 前缀到 space 后缀)。
这是我的代码:
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
我的小学校项目有点复杂,因此我正在寻求帮助。我有一个数据来自 Col1 中的一些文本,我用它来提取最大数值。现在,我一直在尝试使用提取的数字来提取它前后的任何字符(从 space 前缀到 space 后缀)。
这是我的代码:
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