[英]How can I visualize time data from a Pandas Dataframe?
偶尔我会有时间数据,我只想可视化事件发生的频率。 所以我基本上有一个日期时间列表,我想用
所以基本上它是一个直方图,按小时分组
我已经有一个解决方案,但是如何确保所有24个垃圾箱都存在? (它看起来也可能更好)
#!/usr/bin/env python
"""Create and visualize date with timestamps."""
# core modules
from datetime import datetime
import random
# 3rd party module
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
def create_data(num_samples, year, month_p=None, day_p=None):
"""
Create timestamp data.
Parameters
----------
num_samples : int
year: int
month_p : int, optional (default: None)
day_p : int, optional (default: None)
Returns
-------
data : Pandas.Dataframe object
"""
data = []
for _ in range(num_samples):
if month_p is None:
month = random.randint(1, 12)
else:
month = month_p
if day_p is None:
day = random.randint(1, 28)
else:
day = day_p
hour = int(np.random.normal(loc=7) * 3) % 24
minute = random.randint(0, 59)
data.append({'date': datetime(year, month, day, hour, minute)})
data = sorted(data, key=lambda n: n['date'])
return pd.DataFrame(data)
def visualize_data(df):
"""
Plot data binned by hour.
x-axis is the hour, y-axis is the number of datapoints.
Parameters
----------
df : Pandas.Dataframe object
"""
df.groupby(df["date"].dt.hour).count().plot(kind="bar")
plt.show()
df = create_data(2000, 2017)
visualize_data(df)
如您所见,缺少7、9和10。
使用所有值对所得的DataFrame 重新索引 ,然后调用plot方法:
res = df.groupby(df["date"].dt.hour).count().reindex(np.arange(24), fill_value=0)
res.plot(kind="bar")
plt.show()
试试这个功能:
def visualize_data(df):
"""
Plot data binned by hour.
x-axis is the hour, y-axis is the number of datapoints.
Parameters
----------
df : Pandas.Dataframe object
"""
y = df.groupby(df["date"].dt.hour).count()
for i in range(24):
y.loc[i] = 0 if i not in y.index else y.loc[i] # Add missing locations.
y.sort_index(inplace = True) # Sort the locations.
y.plot(kind="bar")
plt.show()
matplotlib.style.use('ggplot')
参见-https://pandas.pydata.org/pandas-docs/stable/visualization.html
如您所见,缺少7、9和10。
O事件?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.