Plotting results of Pandas GroupBy

后端 未结 1 973
走了就别回头了
走了就别回头了 2020-12-07 18:46

I\'m starting to learn Pandas and am trying to find the most Pythonic (or panda-thonic?) ways to do certain tasks.

Suppose we have a DataFrame with columns A, B, and

相关标签:
1条回答
  • 2020-12-07 19:38

    I think @herrfz hit all the high points. I'll just flesh out the details:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    sin = np.sin
    cos = np.cos
    pi = np.pi
    N = 100
    
    x = np.linspace(0, pi, N)
    a = sin(x)
    b = cos(x)
    
    df = pd.DataFrame({
        'A': [True]*N + [False]*N,
        'B': np.hstack((a,b))
        })
    
    for key, grp in df.groupby(['A']):
        plt.plot(grp['B'], label=key)
        grp['D'] = pd.rolling_mean(grp['B'], window=5)    
        plt.plot(grp['D'], label='rolling ({k})'.format(k=key))
    plt.legend(loc='best')    
    plt.show()
    

    enter image description here

    0 讨论(0)
提交回复
热议问题