【问题标题】:plot dataframe columns via for loop通过 for 循环绘制数据框列
【发布时间】:2020-07-01 00:38:34
【问题描述】:

我有以下代码:

dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.random.randn(6, 6), index=dates, columns=["a","b","c","a_x","b_x","c_x"])

结果如下:

                a           b            c         a_x         b_x         c_x
2013-01-01  -0.871681   0.938965    -0.804039   0.329384    -1.211573   0.160477
2013-01-02  1.673895    2.017654    2.181771    0.336220    0.389709    0.246264
2013-01-03  -0.670211   -0.561792   -0.747824   -0.837123   0.129040    1.044153
2013-01-04  -0.571023   -0.430249   0.024393    1.017622    1.072909    0.816249
2013-01-05  0.074952    -0.119953   0.245248    2.658196    -1.525059   1.131054
2013-01-06  0.203816    0.379939    -0.162919   -0.674444   -0.650636   0.415143

我想生成简单的折线图——一共三个,每一个都绘制成对:

a and a_x, b and b_x and c and c_x

我知道如何生成图表,但是由于表格很大并且在列命名约定中具有相同的模式,我在想是否可以通过 for 循环来实现。例如,原始表会有column d and column d_x,还有column e and e_x 等。

【问题讨论】:

    标签: python pandas for-loop matplotlib


    【解决方案1】:

    您可以使用groupbyaxis=1,按拆分列名称的第一个元素分组:

    for _, data in df.groupby(df.columns.str.split('_').str[0], axis=1):
        data.plot()
    

    [出]

    【讨论】:

      猜你喜欢
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 2020-09-19
      • 2022-01-20
      相关资源
      最近更新 更多