pandas 如何在数据框中绘制行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41747039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:49:21  来源:igfitidea点击:

How to plot rows in dataframe

pythonpandasmatplotlib

提问by sandepp

I have dataset which look like this`

我有看起来像这样的数据集`

"Name of Countries","2001","2002","2003","2004","2005","2006","2007","2008","2009","2010"
"BANGLADESH","431312","435867","454611","477446","456371","484401","480240","541884","468899","431962" 
"SRILANKA","112813","108008","109098","128711","136400","154813","204084","218805","239995","266515" 
"UK","405472","387846","430917","555907","651803","734240","796191","776530","769251","759494" 
"USA","329147","348182","410803","526120","611165","696739","799062","804933","827140","931292"

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

我想用 y 轴作为值和 x 轴作为年份来绘制行,例如。我为美国试过

t=df[df['Name of Countries']=='USA']
x=pd.DataFrame([t.iloc[0].index,t.iloc[0].values]).T
x.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. `

我想要 -USA 在图例和 X 轴作为列的名称 [2001,2002...2010],并且可以以更好的方式完成,而无需像我一样通过单个行。`

回答by RobatStats

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 时指定国家名称是您的索引。此外,在我看来,为了您的目的,使用国家作为列和年份作为行将是一个更明智的选择。

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 后,一切都变得非常简单:

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