🤟致敬讀者
- 🟩感謝閱讀🟦笑口常開🟪生日快樂?早點睡覺
📘博主相關
- 🟧博主信息🟨博客首頁🟫專欄推薦🟥活動信息
文章目錄
- Python Pandas讀取Excel表格中數據并根據時間字段篩選數據
- 1. 需求描述
- 2. 讀取excel表格
- 3. 篩選最新時間
- 4. 篩選具體月份數據
- 5.輸出結果
- 6. 完整代碼
📃文章前言
- 🔷文章均為學習工作中整理的筆記。
- 🔶如有錯誤請指正,共同學習進步。
Python Pandas讀取Excel表格中數據并根據時間字段篩選數據
1. 需求描述
現在有一個excel表格,其中包含設備字段device_id、最后使用時間字段end_time以及其他字段若干
需要將表格中的每個設備對應的最新的使用時間篩選出來,并在結果中根據最新時間篩選出4月和5月
對應的設備號列表
2. 讀取excel表格
import pandas as pd# 讀取 Excel 文件
file_path = r"C:\Users\Downloads\file_record.xlsx" # 替換為你的文件路徑
df = pd.read_excel(file_path)
# 顯示前幾行數據
# print(df.head())
# print(df)
3. 篩選最新時間
先根據時間重置DataFrame對象
# Assuming 'df' is your DataFrame and 'end_time' is initially in string format
df['end_time'] = pd.to_datetime(df['end_time']) # Convert to datetime if necessary
然后根據設備號分組,再取end_time中最新即最大時間值,并重置索引
# Group by 'device_id' and find the max (latest) 'end_time' for each group
latest_end_times = df.groupby('device_id')['end_time'].max().reset_index()
4. 篩選具體月份數據
在上面的最新時間中篩選出4月和5月的設備列表
# Filter the 'latest_end_times' DataFrame to only include devices with 'end_time' in April or May
filtered_devices = latest_end_times[(latest_end_times['end_time'].dt.month == 4) | (latest_end_times['end_time'].dt.month == 5)
]
5.輸出結果
遍歷結果中設備和時間信息
for index, row in filtered_devices.iterrows():device_id = row['device_id']latest_end_time = row['end_time']print(f"Device ID: {device_id}, Latest End Time: {latest_end_time}")# 'filtered_devices' now contains the device information for which the latest 'end_time' is in April or May
6. 完整代碼
完整代碼如下
import pandas as pd# 讀取 Excel 文件
file_path = r"C:\Users\Downloads\file_record.xlsx" # 替換為你的文件路徑
df = pd.read_excel(file_path)# 顯示前幾行數據
# print(df.head())
# print(df)# Assuming 'df' is your DataFrame and 'end_time' is initially in string format
df['end_time'] = pd.to_datetime(df['end_time']) # Convert to datetime if necessary
# print(df.head())# Group by 'device_id' and find the max (latest) 'end_time' for each group
latest_end_times = df.groupby('device_id')['end_time'].max().reset_index()
# print(df)# Filter the 'latest_end_times' DataFrame to only include devices with 'end_time' in April or May
filtered_devices = latest_end_times[(latest_end_times['end_time'].dt.month == 4) | (latest_end_times['end_time'].dt.month == 5)
]for index, row in filtered_devices.iterrows():device_id = row['device_id']latest_end_time = row['end_time']print(f"Device ID: {device_id}, Latest End Time: {latest_end_time}")# 'filtered_devices' now contains the device information for which the latest 'end_time' is in April or May
📜文末寄語
- 🟠關注我,獲取更多內容。
- 🟡技術動態、實戰教程、問題解決方案等內容持續更新中。
- 🟢《全棧知識庫》技術交流和分享社區,集結全棧各領域開發者,期待你的加入。
- 🔵?加入開發者的《專屬社群》,分享交流,技術之路不再孤獨,一起變強。
- 🟣點擊下方名片獲取更多內容🍭🍭🍭👇