[英]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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.