使用Pandas中的索引进行切片 [英] Slicing using the Index in Pandas

查看:480
本文介绍了使用Pandas中的索引进行切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试切割与2010年相对应的值,但我收到一条错误消息,我无法解释。

I am trying to slice the value corresponding to the Year 2010 but I get an error message I can not explain.

df1

    GDP USA_GDP_Deflator
Year        
2005    14408093840400  90.877573
2006    14792303791800  93.669574
2007    15055395304800  96.162437
2008    15011490541400  98.048771
2009    14594842181900  98.793388
2010    14964372000000  100.000000
2011    15204019634600  102.064628
2012    15542161722300  103.944710
2013    15802855301300  105.623425
2014    16208861247400  107.519021

df1.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 10 entries, 2005 to 2014
Data columns (total 2 columns):
GDP                 10 non-null int64
USA_GDP_Deflator    10 non-null float64
dtypes: float64(1), int64(1)
memory usage: 240.0 bytes

df1[2010]
KeyError: 2010

您的建议将不胜感激。

推荐答案

我认为需要 DataFrame.loc ,否则pandas会查找列名 2010 ,因为不存在错误引发错误:

I think need DataFrame.loc, else pandas looking for column name 2010 and because does not exist error is raised:

df1.loc[2010]







#rename column for 2010 column
df1 = df1.rename(columns={'USA_GDP_Deflator':2010})
print (df1)
                 GDP        2010
Year                            
2005  14408093840400   90.877573
2006  14792303791800   93.669574
2007  15055395304800   96.162437
2008  15011490541400   98.048771
2009  14594842181900   98.793388
2010  14964372000000  100.000000
2011  15204019634600  102.064628
2012  15542161722300  103.944710
2013  15802855301300  105.623425
2014  16208861247400  107.519021







#selected column 2010
print(df1[2010])
Year
2005     90.877573
2006     93.669574
2007     96.162437
2008     98.048771
2009     98.793388
2010    100.000000
2011    102.064628
2012    103.944710
2013    105.623425
2014    107.519021
Name: 2010, dtype: float64

#selected row 2010
print(df1.loc[2010])
GDP     1.496437e+13
2010    1.000000e+02
Name: 2010, dtype: float64

这篇关于使用Pandas中的索引进行切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆