绘制groupby大熊猫的groupby

时间:2019-11-29 22:12:09

标签: python pandas for-loop matplotlib pandas-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'”错误。

我想要的是一个循环,该循环在每个类别中吐出一张图表,并在每个图表上绘制所有成员的数据

2 个答案:

答案 0 :(得分:1)

不喜欢熊猫的专家,但是如果您执行以下足够简单的代码段

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()

您生成此图 enter image description here

但是可能有更好的方法。

编辑:根据对您的问题所做的更改,我将代码段更改为

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()

现在显示

enter image description here

答案 1 :(得分:1)

创建数据框

import pandas as pd

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']})

然后 [评论后编辑]

import matplotlib.pyplot as plt
import numpy as np

subplots_n = np.unique(data_df['category']).size
subplots_x = np.round(np.sqrt(subplots_n)).astype(int)
subplots_y = np.ceil(np.sqrt(subplots_n)).astype(int)

for i, category in enumerate(data_df.groupby('category')):
    category_df = pd.DataFrame(category[1])
    x = [str(x) for x in category_df['member']]
    y = [float(x) for x in category_df['data']]
    plt.subplot(subplots_x, subplots_y, i+1)
    plt.plot(x, y)
    plt.title("Category {}".format(category_df['category'].values[0]))

plt.tight_layout()
plt.show()

收益

pandas groupby subplots

请注意,这很好地照顾了较大的团体,例如

data_df2 = pd.DataFrame({'category': [1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 5],
                    'member': ['bob', 'joe', 'jim', 'sally', 'jane', 'doe', 'ric', 'mat', 'pip', 'zoe', 'qui', 'quo', 'qua'],
                    'data': ['23', '20', '20', '11', '16', '62', '34', '27', '12', '7', '9', '13', '7']})

pandas groupby subplots

相关问题