0

I have a large Pandas dataframe with a lot of columns and I need to plot a chart per row.

For now I have this in my code:

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)

But the df2 dataframe inside the for loop is empty...

1
  • You don't need a loop. There is a cleaner way to do it. See my answer below. Commented Mar 18, 2020 at 11:13

2 Answers 2

1

Do you need df2 for other operations? If not you can skip that step and create your chart directly by using the row variable by changing your code to:

for index,row in df.iterrows():
    plt.bar(row.keys(),row.values)
    plt.savefig('./plots/chart_' + index)
Sign up to request clarification or add additional context in comments.

Comments

0

An efficient and clean way to plot pandas df per row is to transpose it.

Suppose we happened to have a small df with 13 columns:

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

Plot per column:

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

enter image description here

Plot per row:

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

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.