我的小學校專案變得有點復雜,因此我正在尋求幫助。我有一個資料來自 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
uj5u.com熱心網友回復:
你可以試試:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/347955.html
下一篇:使用字串作為位元組
