力扣:197. 上升的温度(Python3)

题目:

表: Weather

复制代码
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| recordDate    | date    |
| temperature   | int     |
+---------------+---------+
id 是该表具有唯一值的列。
该表包含特定日期的温度信息

编写解决方案,找出与之前(昨天的)日期相比温度更高的所有日期的 id 。

返回结果 无顺序要求 。

结果格式如下例子所示。

来源:力扣(LeetCode)

链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

示例:

示例 1:

输入:

复制代码
Weather 表:
+----+------------+-------------+
| id | recordDate | Temperature |
+----+------------+-------------+
| 1  | 2015-01-01 | 10          |
| 2  | 2015-01-02 | 25          |
| 3  | 2015-01-03 | 20          |
| 4  | 2015-01-04 | 30          |
+----+------------+-------------+

输出:

复制代码
+----+
| id |
+----+
| 2  |
| 4  |
+----+

解释:

复制代码
2015-01-02 的温度比前一天高(10 -> 25)
2015-01-04 的温度比前一天高(20 -> 30)

解法:

先根据日期排序,接着比对后一天是不是和当前间隔1天且温度更高。

知识点:

1.pd.Timedelta(value, unit=None, **kwargs) **:**表示两个datetime值之间的差。value:日期形式字符串;unit:指定value的类型。创建方式比如:

复制代码
pd.Timedelta(days=1)

表示间隔1天。

代码:

python 复制代码
import pandas as pd

def rising_temperature(weather: pd.DataFrame) -> pd.DataFrame:
    weather.sort_values('recordDate', inplace=True)
    w = list(zip(weather['id'], weather['recordDate'], weather['temperature']))
    return pd.DataFrame({'id': [w[index][0] for index in range(1, len(w)) if w[index][1] - w[index - 1][1] == pd.Timedelta(days=1) and w[index][2] > w[index - 1][2]]})
相关推荐
用户8356290780517 分钟前
使用 Python 拆分和提取 PDF 页面
后端·python
用户8356290780518 分钟前
使用 Python 操作 PowerPoint 中的图片
后端·python
梅雅达编程笔记11 分钟前
02_BeautifulSoup网页数据提取
开发语言·爬虫·python·beautifulsoup·数据采集
ai小陈16 分钟前
深度学习CUDA OOM排查:显存占用与碎片问题实战
服务器·人工智能·python·深度学习·ai·gpu算力
小小张说故事39 分钟前
pandas 读大 CSV 太慢?6 个实测提速技巧(dtype / 分块 / 引擎选择)
后端·python·pandas
yi01143 分钟前
DAY17: LeetCode 139|单词拆分:从“把单词删掉”到用 DP 记录合法切口
人工智能·笔记·python·算法·leetcode·动态规划
Java的搬运工1 小时前
【无标题】
python·机器学习·docker·fastapi·模型部署·mlops·ai工程化
陈希瑞1 小时前
LongCat-2.5-Preview 的web逆向能力实测
人工智能·算法·wasm
小小张说故事1 小时前
SHAP 可解释性入门:模型为什么这么判?Python 实战 + 4 个最常见的误读
后端·python·机器学习
codists2 小时前
2026年8月文章一览
python