【问题标题】:How to plot rows in dataframe如何在数据框中绘制行
【发布时间】:2017-01-19 16:36:35
【问题描述】:

我的数据集看起来像这样

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)

我正在尝试以 y 轴为值,x 轴为年份来绘制行,例如。我为美国尝试过

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() 

这完全是丑陋的代码,. 我得到的是

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

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您需要在加载 df 时指定 Name of countries 是您的索引。此外,在我看来,出于您的目的,使用国家作为列和年份作为行将是一个更明智的选择。

    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
    

    以这种方式加载 df 后,一切都变得非常简单:

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

    【讨论】:

      【解决方案2】:

      如果您不想转置数据框,可以使用df.iterrows()

      for index, row in df.iterrows():
          plt.plot(row)
          plt.show()
      

      这将在新图形上绘制数据框的每一行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-12
        • 2020-08-23
        • 2021-11-07
        • 2021-12-24
        • 1970-01-01
        相关资源
        最近更新 更多