从字符串提取数值(正则表达式求助):DataFrame中提取城市温度值
从DataFrame字符串中提取温度数值的方法
核心思路
利用正则表达式匹配文本中的数值,结合pandas的str.extract()方法批量处理DataFrame的文本列,快速提取每个城市对应的温度值。
具体实现方法
方法1:通用匹配所有浮点数/整数
如果文本里的温度可能是整数(如22)或小数(如35.5),可以用兼容两种格式的正则表达式:
import pandas as pd # 示例DataFrame df = pd.DataFrame({ 'city_desc': [ "NYC experienced a temperature of 35.5 degrees centigrade", "London had a high of 22 degrees today", "Tokyo recorded 18.7 degrees centigrade this afternoon" ] }) # 提取温度并转为数值类型 df['temperature'] = df['city_desc'].str.extract(r'(\d+\.?\d*)').astype(float) # 输出结果 print(df)
输出结果会新增一列temperature,对应每个字符串里的温度数值:
city_desc temperature 0 NYC experienced a temperature of 35.5 degrees c... 35.5 1 London had a high of 22 degrees today 22.0 2 Tokyo recorded 18.7 degrees centigrade this af... 18.7
方法2:精准匹配固定结构文本
如果你的文本格式统一(比如都包含"temperature of X degrees"),可以用更精准的正则,避免匹配文本中其他无关数值:
df['temperature'] = df['city_desc'].str.extract(r'temperature of (\d+\.\d+) degrees').astype(float)
这个正则只会捕获"temperature of "和" degrees"之间的小数数值,适合格式高度统一的场景。
注意事项
- 如果需要提取所有匹配的数值(比如文本中有多个数值),可以改用
str.extractall()方法。 - 若提取后出现
NaN,说明对应的字符串中没有匹配到符合规则的数值,需要检查文本格式或调整正则表达式。
内容的提问来源于stack exchange,提问作者Jamie
相关产品推荐
相关产品推荐

