【问题标题】:Pandas line plot without transposing the dataframe熊猫线图不转置数据框
【发布时间】:2020-03-07 19:42:06
【问题描述】:

我有一个看起来像这样的 pandas 数据框 -

    Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Marks
0   30  31  29  15  30  30  30  50  30  30  30  26  Student1
1   45  45  45  45  41  45  35  45  45  45  37  45  Student2
2   21  11  21  21  21  21  21  21  21  21  17  21  Student3
3   30  30  33  30  30  30  50  30  30  30  22  30  Student4
4   39  34  34  34  34  34  23  34  40  34  34  34  Student5
5   41  41  41  28  41  56  41  41  41  41  41  41  Student6

如果我像下面这样转置数据,我可以绘制折线图

    Marks   Student1    Student2    Student3    Student4    Student5    Student6
0   Jan       30          45          21          30          39           41
1   Feb       31          45          11          30          34           41
2   Mar       29          45          21          33          34           41
3   Apr       15          45          21          30          34           28
4   May       30          41          21          30          34           41
5   Jun       30          45          21          30          34           56
6   Jul       30          35          21          50          23           41
7   Aug       50          45          21          30          34           41
8   Sep       30          45          21          30          40           41
9   Oct       30          45          21          30          34           41
10  Nov       30          37          17          22          34           41
11  Dec       26          45          21          30          34           41

但是,我的原始数据非常庞大,转置需要的时间太长。还有其他方法可以实现吗?

请注意 - 这只是我为简单起见创建的一个虚拟数据框,我的原始数据非常复杂且庞大。

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    如果你的数据很大,你可能无论如何都看不到折线图上的任何东西......

    import matplotlib.pyplot as plt
    import pandas as pd
    from io import StringIO
    import numpy as np
    
    df = pd.read_table(StringIO("""    Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Marks
    0   30  31  29  15  30  30  30  50  30  30  30  26  Student1
    1   45  45  45  45  41  45  35  45  45  45  37  45  Student2
    2   21  11  21  21  21  21  21  21  21  21  17  21  Student3
    3   30  30  33  30  30  30  50  30  30  30  22  30  Student4
    4   39  34  34  34  34  34  23  34  40  34  34  34  Student5
    5   41  41  41  28  41  56  41  41  41  41  41  41  Student6"""), sep='\s+')
    
    
    x = df.columns.tolist()[:-1]
    y = df.iloc[:, :-1].values
    for i, j in enumerate(y):
        plt.plot(x, j, label=df['Marks'].iloc[i])
    plt.ylim(bottom=0)
    plt.legend(loc='upper right')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-16
      • 2017-03-20
      • 2018-03-19
      • 1970-01-01
      • 2018-05-11
      • 2022-01-23
      • 2015-07-08
      • 2017-12-16
      相关资源
      最近更新 更多