0

My data is organized like this:

enter image description here

Where country code is the index of the data frame and the columns are the years for the data. First, is it possible to plot line graphs (using matplotlib.pylot) over time for each country without transforming the data any further?

Second, if the above is not possible, how can I make the columns the index of the table so I can plot time series line graphs?

Trying df.t gives me this:

enter image description here

How can I make the dates the index now?

4
  • This is a poor design choice. Years should be index, countries should be columns. Commented Mar 7, 2014 at 3:22
  • I figured so, that's why I posed my second question. Commented Mar 7, 2014 at 3:24
  • I don't understand the question. Transpose will make years into index. Commented Mar 7, 2014 at 3:39
  • Do df = df[df.index != 'Country Code'] before transposing, or del df['Country Code'] after. Commented Mar 7, 2014 at 3:49

1 Answer 1

1
  1. Transpose using df.T.

  2. Plot as usual.

Sample:

import pandas as pd
df = pd.DataFrame({1990:[344,23,43], 1991:[234,64,23], 1992:[43,2,43]}, index = ['AFG', 'ALB', 'DZA'])
df = df.T
df

      AFG  ALB  DZA
1990  344   23   43
1991  234   64   23
1992   43    2   43

# transform index to dates
import datetime as dt
df.index = [dt.date(year, 1, 1) for year in df.index]
import matplotlib.pyplot as plt
df.plot()
plt.savefig('test.png')

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, the dates are the index now, but I am getting this error when I plot: x and y must have same first dimension. I assume it is because the Country Code name is messing up the dimensions. How can I remove 'Country Code'?

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.