python - 绘制 groupby 熊猫的 groupby
问题描述
数据是一个时间序列,有许多成员 ID 与许多类别相关联:
data_df = pd.DataFrame({'Date': ['2018-09-14 00:00:22',
'2018-09-14 00:01:46',
'2018-09-14 00:01:56',
'2018-09-14 00:01:57',
'2018-09-14 00:01:58',
'2018-09-14 00:02:05'],
'category': [1, 1, 1, 2, 2, 2],
'member': ['bob', 'joe', 'jim', 'sally', 'jane', 'doe'],
'data': ['23', '20', '20', '11', '16', '62']})
大约有 50 个类别,有 30 个成员,每个类别有大约 1000 个数据点。
我正在尝试为每个类别制作一个情节。
通过对每个类别进行子集化,然后通过以下方式绘制:
fig, ax = plt.subplots(figsize=(8,6))
for i, g in category.groupby(['memeber']):
g.plot(y='data', ax=ax, label=str(i))
plt.show()
这适用于单个类别,但是,当我尝试使用 for 循环为每个类别重复此操作时,它不起作用
tests = pd.DataFrame()
for category in categories:
tests = df.loc[df['category'] == category]
for test in tests:
fig, ax = plt.subplots(figsize=(8,6))
for i, g in category.groupby(['member']):
g.plot(y='data', ax=ax, label=str(i))
plt.show()
产生“AttributeError:'str'对象没有属性'groupby'”错误。
我想要的是一个循环,每个类别吐出一个图表,所有成员的数据都绘制在每个图表上
解决方案
远非熊猫专家,但如果您执行以下足够简单的代码片段
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'Date': ['2018-09-14 00:00:22',
'2018-09-14 00:01:46',
'2018-09-14 00:01:56',
'2018-09-14 00:01:57',
'2018-09-14 00:01:58',
'2018-09-14 00:02:05'],
'category': [1, 1, 1, 2, 2, 2],
'Id': ['bob', 'joe', 'jim', 'sally', 'jane', 'doe'],
'data': ['23', '20', '20', '11', '16', '62']})
fig, ax = plt.subplots()
for item in df.groupby('category'):
ax.plot([float(x) for x in item[1]['category']],
[float(x) for x in item[1]['data'].values],
linestyle='none', marker='D')
plt.show()
但可能有更好的方法。
编辑:根据对您的问题所做的更改,我将代码段更改为
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.DataFrame({'Date': ['2018-09-14 00:00:22',
'2018-09-14 00:01:46',
'2018-09-14 00:01:56',
'2018-09-14 00:01:57',
'2018-09-14 00:01:58',
'2018-09-14 00:02:05'],
'category': [1, 1, 1, 2, 2, 2],
'Id': ['bob', 'joe', 'jim', 'sally', 'jane', 'doe'],
'data': ['23', '20', '20', '11', '16', '62']})
fig, ax = plt.subplots(nrows=np.unique(df['category']).size)
for i, item in enumerate(df.groupby('category')):
ax[i].plot([str(x) for x in item[1]['Id']],
[float(x) for x in item[1]['data'].values],
linestyle='none', marker='D')
ax[i].set_title('Category {}'.format(item[1]['category'].values[0]))
fig.tight_layout()
plt.show()
现在显示
推荐阅读
- numpy - numpy 切片螺丝图像颜色 (werid)
- javascript - 铯将相机绑定到模型
- python - 提取多边形的坐标
- java - 自定义 WebDriver 无法与 Selenium Actions 方法交互
- ios - 如何使用 VMware 在 PC 上构建 Flutter for iOS
- android - 在android中通过ssh连接到路由器
- java - 如何在java中使用接口从超类实现抽象函数
- excel - 如何使用公式比较数组中的值
- oracle - ORA-00036: 递归 SQL 级别错误
- python - Pandas:按每个单元格的不同值分组并将列拆分为多列