首页 > 解决方案 > 熊猫数据框:从列中的字符串中提取浮点值

问题描述

我正在尝试从特定列的字符串中提取浮动值。

原始输出

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)

输出最终看起来像这样,它显示显示的主整数......

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

我想要的输出将是:

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

感谢您的时间和投入!

编辑:我忘了提到在我的原始数据框中有类似的 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 

带来不便敬请谅解!

标签: pythonregexpandas

解决方案


尝试:

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

输出:

       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

推荐阅读