2

I want to generate a table as below in python with pandas:

            January            February 
          target    achieved    target  achieved
North       23         11         30       29
Center      30         9          27       20
South       14         10         10       10

So that I can plot the chart as below:

enter image description here

I started coding as below but I don't know how to continue with the code:

import pandas as pd
import matplotlib
%matplotlib inline
data = { "target":[23,30,14], "achieved":[11,9,10]}
df=pd.DataFrame(data, index = ["North", "Center", "South"], columns = ['target', 'achieved'] )
df

    target  achieved
North   23  11
Center  30  9
South   14  10

df.plot(kind='bar')

df.plot(kind='bar')

1 Answer 1

2

I think everything you want to know is here: https://pandas.pydata.org/pandas-docs/stable/advanced.html

IMO, you should just copy and paste stuff from there and with trial and error figure out how it works, also be more specific with your question instead of saying "i don't know how to continue" it's better if you write that you want to know how to place another level of columns on top your existing dataframe.

I've made some code that you might be able to use to continue:

arrays = [['January', 'January', 'February', 'February'],
['Target', 'Achieved', 'Target', 'Achieved']]

tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples)


df = pd.DataFrame(np.random.randn(3, 4), index=['North', 'Center', 'South'], columns=index)
print(df)
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the tip but it is a lot for me. I cant understand how I can apply those instructions to my problem.
I've made it a little more clear with an example that applies to your case, i've never worked with multiindexing myself, but just with using code that is on that documentation you can get pretty far.

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.