每行数据框熊猫图

时间:2020-03-18 10:39:09

标签: python-3.x pandas dataframe matplotlib

我有一个大的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数据帧为空...

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

每行绘制熊猫df的有效且干净的方法是将其转置。

假设我们碰巧有一个小的df,其中有13列:

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

每列的图:

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

enter image description here

每行图:

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

enter image description here