python - 从列中提取数字以在 Pandas 中创建新列
问题描述
我有一个名为 Rate 的列,如下所示。我要做的就是创建一个新列Rate_New,它只从Rate 中提取数字部分,即0.25。怎么做?谢谢!!
import pandas as pd
df = pd.DataFrame({'Rate':['$0.25/Wh', '$0.25/Wh', '$0.25/Wh', '$0.25/Wh']})
df
解决方案
这是我的解决方案,您可以复制并粘贴以使用它:
df['Rate_New'] = df.Rate.apply(lambda x: float(x.replace("$","").replace("/Wh","")))
或者这个,没有应用,没有属性:
df["Rate"].str.replace("$","").str.replace("/Wh","")
这是使用正则表达式的版本,没有属性样式不适用。
repl = lambda m: m.group(1)
df["Rate"].str.replace(r'\$(.+?)\/Wh', repl, regex=True)
推荐阅读
- javascript - 如何从表格中删除表格行元素的模式?
- c# - Radgrid:引用与 ItemTemplate 中的文本框在同一行上的控件
- assembly - 读取第二个 BMP 文件时汇编程序崩溃
- go - 为什么 Go 根据我声明缓冲区的位置设置不同的内容类型
- git - 可以将 Visual Studio 设置为在我去编辑文件时自动使文件可写吗?
- c - 如何在 x86-64 上将 80 位长 double 的尾数作为 int
- r - 根据 R 中两个表的信息构建稀疏表
- css - 强制图像具有相同的形状,但仍保持响应
- python - np.mean 的 Numba 失败
- javascript - 在tippy.js工具提示中延迟加载图像?