python - 熊猫数据框:从列中的字符串中提取浮点值
问题描述
我正在尝试从特定列的字符串中提取浮动值。
原始输出
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
带来不便敬请谅解!
解决方案
尝试:
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
推荐阅读
- javascript - 如何自定义 chart.js 工具提示?两个标签有相同的数据,我想用每个数据给你看
- javascript - 临时数据消息如何隐藏
- python-3.x - 使用 for 命令更改 Pandas DF 中的列数据类型
- python-3.x - 无法在 Mac 上安装 AWS CLI
- javascript - 在 React.js 电子商务项目中实现“AddToCard”
- java - 递归循环再次运行而无需在 Java 中调用它
- android - 如何调整 2 个动态 android 布局的大小以填充可用空间,如果两者都想要超过一半,则每个都使用一半?
- spring-boot - 如何定期检查条件直到它通过或持续时间到期
- python - 为什么 python 乘以两个 n 位整数所花费的时间仅在 n 在 10 秒内增加时才会增加?
- sql - Sqlboiler 只获取所需的列