Create Contour Plot from Pandas Groupby Dataframe

前端 未结 2 572
悲&欢浪女
悲&欢浪女 2021-02-02 01:23

I have following Pandas Dataframe:

In [66]: hdf.size()
Out[66]:
a           b
0           0.0          21004
            0.1         119903
            0.2               


        
2条回答
  •  广开言路
    2021-02-02 01:37

    Welcome to SO.

    It looks quite clear that for each of your 'a' level, the numbers of 'b' levels are not the same, thus I will suggest the following solution:

    In [44]:
    
    print df #an example, you can get your dataframe in to this by rest_index()
        a  b     value
    0   0  1  0.336885
    1   0  2  0.276750
    2   0  3  0.796488
    3   1  1  0.156050
    4   1  2  0.401942
    5   1  3  0.252651
    6   2  1  0.861911
    7   2  2  0.914803
    8   2  3  0.869331
    9   3  1  0.284757
    10  3  2  0.488330
    
    [11 rows x 3 columns]
    In [45]:
    #notice that you will have some 'NAN' values
    df=df.pivot('a', 'b', 'value')
    In [46]:
    
    X=df.columns.values
    Y=df.index.values
    Z=df.values
    x,y=np.meshgrid(X, Y)
    plt.contourf(x, y, Z) #the NAN will be plotted as white spaces
    Out[46]:
    
    

    enter image description here

提交回复
热议问题