【问题标题】:Dataframe pandas plot chart per rowDataframe Pandas 每行绘制图表
【发布时间】:2020-03-18 10:39:09
【问题描述】:

我有一个包含很多列的大型 Pandas 数据框,我需要为每行绘制一个图表。

现在我的代码中有这个:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

[...]

df = pd.DataFrame() # DataFrame with 13 columns

for index,row in df.iterrows():
    df2 = pd.DataFrame(row)
    plt.set_title(row)
    plt.bar(df2)
    plt.savefig('./plots/chart_' + index)

但是for循环内的df2数据框是空的...

【问题讨论】:

  • 你不需要循环。有一种更清洁的方法可以做到这一点。请参阅下面的答案。

标签: python-3.x pandas dataframe matplotlib


【解决方案1】:

您需要 df2 进行其他操作吗?如果没有,您可以跳过该步骤并通过将代码更改为使用 row 变量直接创建图表:

for index,row in df.iterrows():
    plt.bar(row.keys(),row.values)
    plt.savefig('./plots/chart_' + index)

【讨论】:

    【解决方案2】:

    每行绘制 pandas df 的一种有效而简洁的方法是转置它。

    假设我们碰巧有一个小 df 有 13 列:

    df = pd.DataFrame(np.random.randn(10,13))
    df.shape
    (10, 13)
    

    每列绘图:

    df.plot.bar()
    plt.legend(df.columns, loc="right");
    

    每行绘图:

    df.T.plot.bar()
    plt.legend(df.columns, loc="right");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-18
      • 2015-06-12
      • 2015-10-23
      • 2016-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多