【问题标题】:Extract number from column to make a new column in Pandas从列中提取数字以在 Pandas 中创建新列
【发布时间】:2020-06-25 19:06:38
【问题描述】:

我有一个名为 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

【问题讨论】:

  • 你应该用regex标记这个,我认为这是你问题的关键
  • @Matt 谢谢,我刚刚添加了标签。
  • 你试过什么?什么没用?你得到了什么?你期待什么?什么不适用于您的代码,它在哪里?
  • 到底是什么问题?你有没有尝试过,做过任何研究? Stack Overflow 不是免费的代码编写服务。请参阅:How to Askhelp centermeta.stackoverflow.com/questions/261592/…

标签: python regex pandas dataframe


【解决方案1】:

首先添加一个从中提取数字的方法 评价,说extract_rate()

def extract_rate(rate):
    return rate.replace('$', '').replace('/Wh', '')

然后,您可以将该方法应用于整个列以生成新列。

df['Rate_new'] = df.apply(lambda row: extract_rate(row['Rate']), axis = 1)t_rate(row['Rate']), axis = 1)

【讨论】:

  • 为什么要使用apply()、一个函数和一个lambda,而不是Pandas提供的字符串操作方法?
【解决方案2】:

这可以通过以下代码来实现,您可以将这些代码放置在单独的 Jupyter 单元中:

    # Import the Pandas and regex libraries 
    import pandas as pd
    import re

    # Use your dataframe
    df = pd.DataFrame({'Rate':['$0.25/Wh', '$0.25/Wh', '$0.25/Wh', '$0.25/Wh']})

    # State regex pattern that extracts the value
    pattern = r"(?:[]{1}[,\d]+.?\d*)"

    # Iterate over rate column of dataframe and perform regex to extract value
    search = []    
    for values in df['Rate']:
        search.append(re.search(pattern, values).group())

    df['Rate_New'] = search

   # Display the result of the dataframe with appended column
    df

【讨论】:

  • 为什么要使用这么复杂的东西呢?
【解决方案3】:

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

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)

【讨论】:

  • 为什么使用属性样式的列访问?更重要的是,您为什么要为此使用 apply() 和 lambda?
  • 请看我的修改版。
  • 你反对使用正则表达式吗?
  • 不反对,请看我的修改版,我以为你说不用lambda?您是否有想法在没有 lambda 的情况下使用正则表达式?顺便说一句,只是出于好奇,我发现这个问题中的一些回复使用了完全相同的解决方案,为什么我被否决了,但他们不是?
  • @sun 我同意。显然有人在这里破坏了大家的学习和分享机会,这对stackoverflow来说真是太糟糕了。
【解决方案4】:

您可以按如下方式替换它们:

df["Rate_new"] = df["Rate"].apply(lambda x: x.replace("$", "").replace("/Wh", ""))

【讨论】:

  • 为什么要使用apply() 和 lambda 而不是 Pandas 提供的字符串操作方法?
【解决方案5】:
df["Rate_New"] = df.Rate.str.replace(r"\$(.+)/Wh", lambda m: m.group(1)).astype(float)
  • 正则表达式有 1 个捕获组 — $/Wh 之间的所有符号。
  • lambda 函数用这个捕获组替换原始字符串。
  • 然后.astype() 方法将数据类型(从“对象”)更改为float

【讨论】:

    【解决方案6】:
    df["Rate_New"] = df.Rate.str.split(r"[$/]").apply(lambda x: x[1]).astype(float)
    
    • .str.split() 方法将原始值转换为列表:

      0    [, 0.25, Wh]
      1    [, 0.25, Wh]
      2    [, 0.25, Wh]
      3    [, 0.25, Wh]
      Name: Rate, dtype: object           
      
    • lambda 函数从这些列表中提取中间元素(即索引为 1):

      0    0.25
      1    0.25
      2    0.25
      3    0.25
      Name: Rate, dtype: object
      
    • .astype() 方法然后将数据类型更改为float

      0    0.25
      1    0.25
      2    0.25
      3    0.25
      Name: Rate, dtype: float64
      
    • df["Rate_New"] = 然后将创建的系列作为新列分配给您的数据框:

             Rate  Rate_New
      0  $0.25/Wh      0.25
      1  $0.25/Wh      0.25
      2  $0.25/Wh      0.25
      3  $0.25/Wh      0.25
      

    【讨论】:

    • 为什么要把事情搞得这么复杂?还有,为什么要使用属性/. 样式进行列访问?
    • 1. 您的不那么复杂的解决方案在哪里? 2. 阅读文档。 @AMC
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多