![](/img/trans.png)
[英]Extracting numerical values from a string with at most 6 digits with optional 2 digits for decimal
[英]Extracting numerical data from string
我在 csv 文件中有這種格式的文本數據:
76.76% @ 26.2° CD:20.7° CG/KG:15.5
日期、值、格式化值
2019-10-11 14:50:00,71.19,71.19% @ 24.4° CD: 17.7° CG/KG: 12.8
2019-10-11 15:00:00,72.2,72.2% @ 24.4° CD: 17.9° CG/KG: 13
2019-10-11 15:10:00,71.35,71.35% @ 24.4° CD: 17.8° CG/KG: 12.9
我想提取每個數字數據並將其存儲在不同的列中。 不過,數字並不總是包含小數位。
編輯:數據來自 csv 文件,我想將每個數字數據存儲在不同的列中。
您可以在此處使用regex
。
import re
a='76.76% @ 26.2° C D: 20.7° C G/KG: 15.5 75' #I added 75 just to show it caputres ints and floats.
nums=re.findall(r'\d+\.\d+|\d+',a)
print(nums)
#['76.76', '26.2', '20.7', '15.5', '75']
在這個例子中,我將數據作為字符串並使用split(' ')
。 您可以使用sep=' '
從 csv 文件中獲取數據。 我也使用過正則表達式,您需要將其導入為import re
data = '76.76% @ 26.2° C D: 20.7° C G/KG: 15.5'
data = data.split(' ')
data = [re.sub("[^0-9.]", "", x) for x in data]
data = [x for x in data if x != '']
temp_dict = {}
for i, item in enumerate(data):
temp_dict[f'col_{i}'] = item
df = pd.DataFrame([temp_dict])
輸出:
col_0 col_1 col_2 col_3
0 76.76 26.2 20.7 15.5
更新
這可能更有用。
df[['col1', 'col2', 'col3', 'col4']] = df['Formatted Value'].str.extractall('(\d+.\d+)').unstack().loc[:, 0]
更新 2
此代碼適用於十進制和整數值。
df = pd.read_csv('test.csv')
my_list = df['Formatted Value'].apply(lambda x: re.findall(r'[\d\.\d]+', x))
d = {'Extractted': my_list}
temp_df = pd.DataFrame(d)
df[['col1', 'col2', 'col3', 'col4']] = pd.DataFrame(temp_df['Extractted'].values.tolist(), index=temp_df.index)
嘗試:
df.join(df['Formatted Value'].str.findall(r'\d+\.\d+|\d+').str.join(' ').str.split(expand=True)).drop('Formatted Value',axis=1)
Date Value 0 1 2 3
0 2019-10-11 14:50:00 71.19 71.19 24.4 17.7 12.8
1 2019-10-11 15:00:00 72.20 72.2 24.4 17.9 13
2 2019-10-11 15:10:00 71.35 71.35 24.4 17.8 12.9
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.