Skip to content Skip to sidebar Skip to footer

Pandas Groupby Plot Values

I have a pandas dataframe that looks like this: **real I SI weights** 0 1 3 0.3 0 2 4 0.2 0 1 3

Solution 1:

Once you do this:

results = df.groupby(['real', 'I', 'SI'])['weights'].sum()

You can get the values of 'real', 'I' and 'SI' stored in the dataframe by using

results.index.get_level_values(0)
Int64Index([0, 0, 0, 1, 1, 1], dtype='int64', name='real'
results.index.get_level_values(1)
Int64Index([1, 1, 2, 1, 2, 2], dtype='int64', name=' I')
results.index.get_level_values(2)
Int64Index([3, 5, 4, 3, 4, 5], dtype='int64', name=' SI')

You can iterate over those to get the plots you want. For example:

import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 2)

for idx1, i inenumerate(results.index.get_level_values(0).unique()):
    for idx2, j inenumerate(results.index.get_level_values(1).unique()):
        axes[idx1, idx2].plot(results.loc[i, j], 'o')
        axes[idx1, idx2].set_xlabel('SI')
        axes[idx1, idx2].set_ylabel('weights')
        axes[idx1, idx2].set_xlim([0, 6])
        axes[idx1, idx2].set_ylim([0, 1])
        axes[idx1, idx2].set_title('real: {} I: {}'.format(i, j))

plt.tight_layout()
plt.show()

which gives

subplots over real, I values

Post a Comment for "Pandas Groupby Plot Values"