【问题标题】:What would be the best way to extract certain numbers after a specific phrase from a string in a column?从列中的字符串中提取特定短语后的某些数字的最佳方法是什么?
【发布时间】:2021-11-21 15:33:08
【问题描述】:

在我正在使用的数据框中,我有一个名为“天气”的列,其中包含如下所示的天气数据:

Sunny Temp: 78� F, Humidity: 63%, Wind: SSW 6 mph
Sunny Temp: 103� F, Humidity: 7%, Wind: 16 SW mph
Temp: 88� F, Humidity: 43%, Wind: S 12 mph
Cloudy Temp: 81� F, Humidity: 90%, Wind: SW 5 mph

我想使用 dplyr 的 mutate 函数为包含在“天气”列中的温度和风速创建新列。对于温度列,我正在考虑一个查看“Temp:”之后的前 3 个字符并提取任何数字的函数应该可以工作。如您所见,对于风,有时风向位于数字之前。因此,与温度列类似的功能,但可能会查看前 6-7 个字符并提取任何数字。

我已经阅读了 sub、gsub、substr 和 str_extract 并尝试针对我的特定困境实施其中的每一个。我只是无法选择我上面描述的特定字符串。例如我试过:

mutate(temperature = sub('.*Temp: ', '',weather)) %>%
mutate(temperature = substr(temp, 1, 2))

但当温度为 1 或 3 位数时,这不起作用。

非常感谢任何帮助!

【问题讨论】:

    标签: r string dplyr stringr


    【解决方案1】:

    我们可以将str_extract 与正则表达式环视一起使用,即在子字符串“Temp:”之后查找一位或多位数字 (\\d+)

    library(dplyr)
    library(stringr)
    df1 %>%
      mutate(temperature = str_extract(weather, "(?<=Temp: )\\d+"),
             Wind = str_extract(weather, "(?<=Wind: [A-Z] )\\d+"))
    

    【讨论】:

    • 谢谢 - 这对于温度列非常有效,但不适用于在实际风速数字前有几个字母的风列。例如:“风速:S 12 mph”——我能做些什么来解决这个问题?
    • 更新了帖子
    【解决方案2】:
    library(dplyr)
    library(stringr)
    df %>%
      mutate(Temperature = str_extract(x, "(?<=Temp:\\s)\\d+"),
             Wind = str_extract(x, "(?<=Wind:\\s[A-Z]{0,5}\\s?)\\d+"))
                                                      x Temperature Wind
    1 Sunny Temp: 78� F, Humidity: 63%, Wind: SSW 6 mph          78    6
    2 Sunny Temp: 103� F, Humidity: 7%, Wind: 16 SW mph         103   16
    3        Temp: 88� F, Humidity: 43%, Wind: S 12 mph          88   12
    4 Cloudy Temp: 81� F, Humidity: 90%, Wind: SW 5 mph          81    5
    

    虽然(?&lt;=Temp: ) 的第一个lookbehind 相对简单,但(?&lt;=Wind:\\s[A-Z]{0,5}\\s?) 的第二个lookbehind 更复杂。这是因为大写字母加上后面的空格可能会在Wind: 和数字之间进行干预。

    数据:

    df <- data.frame(
      x = c("Sunny Temp: 78� F, Humidity: 63%, Wind: SSW 6 mph",
      "Sunny Temp: 103� F, Humidity: 7%, Wind: 16 SW mph",
      "Temp: 88� F, Humidity: 43%, Wind: S 12 mph",
      "Cloudy Temp: 81� F, Humidity: 90%, Wind: SW 5 mph")
    )
    

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 1970-01-01
      • 2013-12-21
      • 1970-01-01
      • 1970-01-01
      • 2012-02-29
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多