如何为数据框的特定子集绘制图形

时间:2019-09-03 10:51:36

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

我一直在尝试为数据的特定子集绘制图形。我的数据包含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:不可哈希类型:'numpy.ndarray'

1 个答案:

答案 0 :(得分: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()