[英]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.