문제
Table: Weather
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| recordDate | date |
| temperature | int |
+---------------+---------+
id is the column with unique values for this table.
There are no different rows with the same recordDate.
This table contains information about the temperature on a certain day.
Write a solution to find all dates' Id with higher temperatures compared to its previous dates (yesterday).
Return the result table in any order.
https://leetcode.com/problems/rising-temperature/description/?lang=pythondata
예시
Input:
Weather table:
+----+------------+-------------+
| id | recordDate | temperature |
+----+------------+-------------+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
+----+------------+-------------+
Output:
+----+
| id |
+----+
| 2 |
| 4 |
+----+
Explanation:
In 2015-01-02, the temperature was higher than the previous day (10 -> 25).
In 2015-01-04, the temperature was higher than the previous day (20 -> 30).
문제 풀이
#1. recordDate에서 1일 빼서 이전 날짜 구하기
weather['prev_recordDate'] = weather['recordDate'] - pd.Timedelta(days=1)
id recordDate temperature prev_recordDate
0 1 2015-01-01 10 2014-12-31
1 2 2015-01-02 25 2015-01-01
2 3 2015-01-03 20 2015-01-02
3 4 2015-01-04 30 2015-01-03
2. prev_recordDate에 temperature 매핑하기
weather['prev_temperature'] = weather['prev_recordDate'].map(weather.set_index('recordDate')['temperature'])
id recordDate temperature prev_recordDate prev_temperature
0 1 2015-01-01 10 2014-12-31 NaN
1 2 2015-01-02 25 2015-01-01 10.0
2 3 2015-01-03 20 2015-01-02 25.0
3 4 2015-01-04 30 2015-01-03 20.0
3. prev_temperature보다 temperature가 큰 id 찾기
result = weather.loc[weather['temperature'] > weather['prev_temperature'], 'id']
0 2
3 4
Name: id, dtype: int64
* 최종 코드 (series가 아니라 df형태로 제출)
import pandas as pd
def rising_temperature(weather: pd.DataFrame) -> pd.DataFrame:
weather['prev_recordDate'] = weather['recordDate'] - pd.Timedelta(days=1)
weather['prev_temperature'] = weather['prev_recordDate'].map(weather.set_index('recordDate')['temperature'])
result = weather.loc[weather['temperature'] > weather['prev_temperature'], 'id']
return result.to_frame()
파이썬을 독학하시는 분들에게 도움이 되길 바라며,
혹 더 좋은 방법이 있거나 오류가 있다면 편하게 말씀 부탁드립니다.