簡體   English   中英

Pandas dataframe:從列中的字符串中提取浮點值

[英]Pandas dataframe: Extracting float values from string in a column

我正在嘗試從特定列的字符串中提取浮動值。

原裝Output

DATE        strCondition
4/3/2018    2.9
4/3/2018    3.1, text
4/3/2018    2.6 text
4/3/2018    text, 2.7 

和其他變體。 我也嘗試過正則表達式,但我在這里的知識有限,我想出了:

clean = df['strCondition'].str.contains('\d+km')
df['strCondition'] = df['strCondition'].str.extract('(\d+)', expand = False).astype(float)

output 最終看起來像這樣,它顯示主要的 integer 顯示...

DATE        strCondition
4/3/2018    2.0
4/3/2018    3.0
4/3/2018    2.0
4/3/2018    2.0 

我想要的 output 將是:

DATE        strCondition
4/3/2018    2.9
4/3/2018    3.1
4/3/2018    2.6
4/3/2018    2.7 

感謝您的時間和投入!

編輯:我忘了提到在我原來的 dataframe 中有類似的 strCondition 條目

2.9(1.0) #where I would like both numbers to get returned
11/11/2018 #where this date as a string object can be discarded 

帶來不便敬請諒解!

嘗試:

df['float'] = df['strCondition'].str.extract(r'(\d+.\d+)').astype('float')

Output:

       DATE strCondition  float
0  4/3/2018          2.9    2.9
1  4/3/2018    3.1, text    3.1
2  4/3/2018     2.6 text    2.6
3  4/3/2018    text, 2.7    2.7

一個簡單的替換將是

查找(?m)^([\d/]+[ \t]+).*?(\d+\.\d+).*

替換\1\2

https://regex101.com/r/pVC4jc/1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM