简体   繁体   中英

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      0.5
        0       1     5      0.5

        1       2     5      0.3  
        1       2     4      0.2
        1       1     3      0.5

I need to divide it by "real", then I need to do the following:

given a value of I, consider each value of SI and add the total weight. At the end, I should have, for each realization, something like that:

    real = 0:
             I = 1     SI = 3      weight = 0.8
                       SI = 5      weight = 0.5

             I = 2     SI = 4      weight = 0.2

    real = 1:  
             I = 1     SI = 3      weight = 0.5

             I = 2     SI = 5      weight = 0.3
                       SI = 4      weight = 0.2

The idea is then to plot, for each value of I and real, on the x axis the values of SI and on the y axis the relative total weight (normalized to 1).

What I tried to do was this:

       name = ['I', 'SI','weight', 'real']
       Location = 'Simulationsdata/prova.csv'
       df = pd.read_csv(Location, names = name,sep='\t',encoding='latin1') 

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

When I print results, I have the table I want, but now I don`t know how to make a plot as I wanted, because I do not know how to get the SI values...

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 in enumerate(results.index.get_level_values(0).unique()):
    for idx2, j in enumerate(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

我重视真实的子图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM