Tod*_*ein 2 python datetime matplotlib dataframe pandas
我有很多年的 15 分钟时间步长数据......
约会时间 | 数量 |
---|---|
2018年1月7日 00:15 | 6.96 |
2018年1月7日 00:30 | 6.48 |
2018年1月7日 00:45 | 6.96 |
2018年1月7日 01:00 | 6.72 |
。 | 。 |
。 | 。 |
我正在使用熊猫。如何生成横轴为月份的条形图;以及每年的一系列(一组条形图);每个条形的高度是该月和该年的总量。
正是这样:
假数据框创建:
df = pd.DataFrame()
df['Datetime'] = pd.date_range(start = '01/07/2018', end = '13/08/2021', freq = '15min')
df['Quantity'] = np.random.rand(len(df))
Run Code Online (Sandbox Code Playgroud)
从这一点开始,您应该提取月份和年份并将它们保存在单独的列中:
df['month'] = df['Datetime'].dt.month
df['year'] = df['Datetime'].dt.year
Run Code Online (Sandbox Code Playgroud)
然后你必须计算'Quantity'
每年每月的总和:
df = df.groupby(by = ['month', 'year'])['Quantity'].sum().reset_index()
Run Code Online (Sandbox Code Playgroud)
读完这篇文章后,您应该有一个像这样的数据框:
Datetime Quantity month year
0 2018-01-07 00:00:00 0.226113 1 2018
1 2018-01-07 00:15:00 0.222872 1 2018
2 2018-01-07 00:30:00 0.835484 1 2018
3 2018-01-07 00:45:00 0.775771 1 2018
4 2018-01-07 01:00:00 0.972559 1 2018
5 2018-01-07 01:15:00 0.418036 1 2018
6 2018-01-07 01:30:00 0.902843 1 2018
7 2018-01-07 01:45:00 0.012441 1 2018
8 2018-01-07 02:00:00 0.883437 1 2018
9 2018-01-07 02:15:00 0.183561 1 2018
Run Code Online (Sandbox Code Playgroud)
现在数据框已准备好绘制;使用seaborn:
fig, ax = plt.subplots()
sns.barplot(ax = ax, data = df, x = 'month', y = 'Quantity', hue = 'year')
plt.show()
Run Code Online (Sandbox Code Playgroud)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.DataFrame()
df['Datetime'] = pd.date_range(start = '01/07/2018', end = '13/08/2021', freq = '15min')
df['Quantity'] = np.random.rand(len(df))
df['month'] = df['Datetime'].dt.month
df['year'] = df['Datetime'].dt.year
df = df.groupby(by = ['month', 'year'])['Quantity'].sum().reset_index()
fig, ax = plt.subplots()
sns.barplot(ax = ax, data = df, x = 'month', y = 'Quantity', hue = 'year')
plt.show()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2776 次 |
最近记录: |