【问题标题】:How do I plot a graph for a specific subset of a dataframe如何为数据框的特定子集绘制图表
【发布时间】:2020-01-06 06:32:57
【问题描述】:

我一直在尝试为我的数据的特定子集绘制图表。我的数据有 1960 年到 2018 年的数据。但是,我只对仅使用特定列的变量和显示 1981 年以后的数据的行来绘制直方图感兴趣。

到目前为止,我已经尝试使用 2 个变量进行绘图

x = df1y.index

返回值:

Int64Index([1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991,
        1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
        2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013,
        2014, 2015, 2016, 2017],
       dtype='int64', name=' Time ')

y = df1.iloc[21:58, [15]] ## 21 to 58 are rows for 1981 to 2017 while column 15 refers to the column I've been trying to get

y 返回:

Resident Live-births(Number)
Time    
1981    41,000
1982    41,300
1983    39,300
1984    40,200
1985    41,100
1986    37,159
1987    42,362
1988    51,537
1989    46,361
1990    49,787
1991    47,805
1992    47,907
1993    48,739
1994    48,075
1995    46,916
1996    46,707
1997    45,356
1998    41,636
1999    41,327
2000    44,765
2001    39,281
2002    38,555
2003    35,474
2004    35,135
2005    35,528
2006    36,272
2007    37,074
2008    37,277
2009    36,925
2010    35,129
2011    36,178
2012    38,641
2013    35,681
2014    37,967
2015    37,861
2016    36,875
2017    35,444

键入后

x = df1y.index
y = df1.iloc[21:58, [15]]
plt.plot(x, y, 'o-')

我收到一个错误:

TypeError: unhashable type: 'numpy.ndarray'

【问题讨论】:

    标签: python python-3.x pandas matplotlib jupyter-notebook


    【解决方案1】:

    使用

    y = df1.iloc[21:58, 15].values
    

    按照你尝试走路的方式去做


    但是,通常你不想自己计算子集索引,所以考虑一下

    y = df1.loc[df1.index > 1981, 'name_of_your_column_15_here'].values
    

    获取您想要的 (y-) 值的 numpy 数组。

    为了获得更多便利,只需尝试将.plot() 直接应用于系列(也适用于整个数据帧),然后看看会发生什么...

    idx_slice = df1.index > 1981
    df1.loc[idx_slice, 'name_of_your_column_15_here'].plot()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      • 2018-11-24
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多