首页 > 解决方案 > 从列中提取数字以在 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

标签: pythonregexpandasdataframe

解决方案


这是我的解决方案,您可以复制并粘贴以使用它:

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)

推荐阅读