Pandas数据帧切片

时间:2016-09-17 14:34:51

标签: python pandas dataframe

我有以下数据框:

    2012   2013   2014   2015  2016   2017   2018                 Kategorie
0   5.31   5.27   5.61   4.34   4.54   5.02   7.07  Gewinn pro Aktie in EUR
1  13.39  14.70  12.45  16.29  15.67  14.17  10.08                      KGV
2 -21.21  -0.75   6.45 -22.63  -7.75   9.76  47.52           Gewinnwachstum
3 -17.78   2.27  -0.55   3.39   1.48   0.34    NaN                      PEG

现在,我只选择KGV行:

df[df["Kategorie"] == "KGV"]

哪个输出:

    2012  2013   2014   2015  2016   2017   2018  Kategorie
1  13.39  14.7  12.45  16.29  15.67  14.17  10.08       KGV

如何计算过去五年的mean()(本例中为2016,15,14,13,12)?
我试过了

df[df["Kategorie"] == "KGV"]["2016":"2012"].mean()

但这会引发TypeError。为什么我不能在这里切片?

3 个答案:

答案 0 :(得分:4)

loc支持这种切片类型(从左到右):

df.loc[df["Kategorie"] == "KGV", "2012":"2016"].mean(axis=1)
Out: 
1    14.5
dtype: float64

请注意,这并不一定意味着2012年,2013年,2014年,2015年和2016年。这些是字符串,因此它表示df['2012']df['2016']之间的所有列。中间可能有一个名为foo的列,它将被选中。

答案 1 :(得分:2)

不确定为什么过去五年是2012-2016(它们似乎是第一个五年)。尽管如此,要查找'KGV'的2012-2016平均值,您可以使用

df[df['Kategorie'] == 'KGV'][[c for c in df.columns if c != 'Kategorie' and 2012 <= int(c) <= 2016]].mean(axis=1)

答案 2 :(得分:2)

我使用了filteriloc

row = df[df.Kategorie == 'KGV']

row.filter(regex='\d{4}').sort_index(1).iloc[:, -5:].mean(1)

1    13.732
dtype: float64
相关问题