2017-06-27 1 views
1

私は奇妙な問題があります。私は正しいかどうかわからない。私はPandasサブセットはPython3.6のインデックスに基づいて動作しないようです

クリックlinkは、以下のコードは

subset = df[['country', 'pop']] 
subset.head() 

任意のエラーを生成しません。しかし、私はインデックスに基づいて部分集合しようとした場合

df = pd.read_csv("./data/gapminder.tsv",sep="\t") 

データセットのpython3.6で、この問題を発見し、エラーが発生しています

subset = df[[0,4]] 
> KeyError: '[0 4] not in index' 

ipython er link

答えて

1

必要としているROR iloc

url = 'https://raw.githubusercontent.com/jennybc/gapminder/master/inst/gapminder.tsv' 
df = pd.read_csv(url, sep="\t") 
print (df.head()) 
     country continent year lifeExp  pop gdpPercap 
0 Afghanistan  Asia 1952 28.801 8425333 779.445314 
1 Afghanistan  Asia 1957 30.332 9240934 820.853030 
2 Afghanistan  Asia 1962 31.997 10267083 853.100710 
3 Afghanistan  Asia 1967 34.020 11537966 836.197138 
4 Afghanistan  Asia 1972 36.088 13079460 739.981106 

subset = df[['country', 'pop']] 
print (subset.head()) 
     country  pop 
0 Afghanistan 8425333 
1 Afghanistan 9240934 
2 Afghanistan 10267083 
3 Afghanistan 11537966 
4 Afghanistan 13079460 

subset = df.iloc[:, [0,4]] 
print (subset.head()) 
     country  pop 
0 Afghanistan 8425333 
1 Afghanistan 9240934 
2 Afghanistan 10267083 
3 Afghanistan 11537966 
4 Afghanistan 13079460 
関連する問題