Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

python - How to plot rows in dataframe

I have dataset which look like this

import pandas as pd

data = {'Name of Countries': ['BANGLADESH', 'SRILANKA', 'UK', 'USA'], '2001': [431312, 112813, 405472, 329147], '2002': [435867, 108008, 387846, 348182], '2003': [454611, 109098, 430917, 410803], '2004': [477446, 128711, 555907, 526120], '2005': [456371, 136400, 651803, 611165], '2006': [484401, 154813, 734240, 696739], '2007': [480240, 204084, 796191, 799062], '2008': [541884, 218805, 776530, 804933], '2009': [468899, 239995, 769251, 827140], '2010': [431962, 266515, 759494, 931292]}
df = pd.DataFrame(data)

I am trying to plot row with y axis as the values and x axis being the year, eg. I tried for USA

t=df[df['Name of Countries']=='USA']
x=pd.DataFrame([t.iloc[0].index,t.iloc[0].values]).T
x.iloc[1:].plot()
plt.show() 

Which is completely ugly looking code, . What I get is enter image description here

I want -USA at legend and X axis as name of columns [2001,2002...2010], and can it be done in a better way, without going through individual row like I am doing.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to specify that Name of Countries is your index when you load the df. Also, it seems to me that for your purposes using countries as columns and years as rows would be a more sensible choice.

df = pd.read_csv(yourcsv, index_col='Name of Countries') #set column as       index
df = df.T #Transpose df, now countries are your columns and years your rows

Once you load the df in that way everything is super easy:

df.USA.plot(legend=True) #plot usa column
plt.show()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...