在 CSV 檔案中,我有我的應用程式的日期、停機時間和事件編號。根據以下資料,我必須使用 Python 繪制我的應用程式正常運行時間圖。過去 7 天的正常運行時間、過去 30 天的正常運行時間和過去 90 天的正常運行時間。
| 日期 | 停機時間(小時) | 事件 |
|---|---|---|
| 2022-10-05 | 2 | abc123 |
| 2022-10-05 | 3 | abc124 |
| 2022-09-01 | 4 | abc100 |
| 2022-08-26 | 8 | abc99 |
| 2022-08-24 | 5 | abc98 |
| 2022-07-15 | 6 | abc90 |
| 2022-06-09 | 4 | abc85 |
我可以使用 pandas 讀取這些資料,并且可以使用以下方法按事件繪制停機時間。
downtime_by_incident = data.groupby(["date", "incident"])['downtime].sum().unstack().plot(kind="bar", stacked=True, xlabel="", legend=False).get_figure()
downtime_by_incident.savefig("downtime_by_incident.jpg", bbox_inches = "tight")
但我無法計算和繪制我的應用程式的正常運行時間。任何幫助將不勝感激
uj5u.com熱心網友回復:
一種方法是創建第二個資料集來跟蹤正常運行時間,以補充您當前跟蹤停機時間的資料集。
import pandas as pd
import numpy as np
from io import StringIO
import plotly.express as px
df = pd.read_csv(StringIO('''date downtime(hrs) incident
2022-10-05 2 abc123
2022-10-05 3 abc124
2022-09-01 4 abc100
2022-08-26 8 abc99
2022-08-24 5 abc98
2022-07-15 6 abc90
2022-06-09 4 abc85'''), sep='\t')
df['date'] = pd.to_datetime(df['date'])
df2 = pd.DataFrame({'date':pd.date_range(df['date'].min(), df['date'].max(),freq='d')}).assign(tot_hours=24)
df2 = pd.merge(df2, df[['date', 'downtime(hrs)']].groupby('date').sum().reset_index(), how='left')
df2['uptime'] = df2['tot_hours'] - df2['downtime(hrs)'].fillna(0)
#if there's any negative downtime, impute to zero
df2['uptime'] = np.where(df2['uptime']<0, 0, df2['uptime'])
fig = px.line(df2,
x='date',
y='uptime')
fig.show()

使用實際資料集,您可以找到最新的正常運行時間,如下所示:
for n in [7,30,90]:
n_days_ago = pd.to_datetime('today').normalize()-pd.Timedelta(n, unit='d')
today = pd.to_datetime('today').normalize()
df2.loc[df2['date'].between(n_days_ago, today), 'uptime'].sum()
#output
0.0
0.0
1370.0
uj5u.com熱心網友回復:
# convert to datetime
df['date'] = pd.to_datetime(df['date'])
# groupby date and sum downtime then merge on a new Frame you create
# that fills in the missing dates
m = df.groupby('date')['downtime(hrs)'].sum().reset_index().merge(pd.DataFrame(pd.date_range(df['date'].min(),
df['date'].max()),
columns=['date']),
on='date', how='right').fillna(0)
# calculate the uptime (24 hours - downtime hours) for each day
m['uptime'] = 24 - m['downtime(hrs)']
# bar plot
m[['date', 'uptime']].set_index('date').plot(kind='bar', figsize=(20,10))
# line plot
m[['date', 'uptime']].set_index('date')['uptime'].plot(figsize=(20,10))
# stacked bar plot
m.set_index('date').plot(kind='bar', stacked=True, figsize=(20,10))

請注意,您可能應該更新此行:
pd.DataFrame(pd.date_range(df['date'].min(), df['date'].max()), columns=['date'])
在你的第一幀中成為今天而不是最后一天
pd.DataFrame(pd.date_range(df['date'].min(), datetime.datetime.today()), columns=['date'])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/529730.html
標籤:Python熊猫matplotlib情节地python-3.8
下一篇:帶有圖例的Pandas直方圖
