LoginSignup
2
1

More than 3 years have passed since last update.

IndexError: index -1 is out of bounds for axis 0 with size 0を解決

Last updated at Posted at 2020-08-14

今回質問をし教えて頂いたので備忘録と共有をします。

IndexError: index -1 is out of bounds for axis 0 with size 0

経緯

東京都の昼間の人口予測のデータから過去から未来にかけての密集地の予測をするため、seabornのpairplotを行おうとした所、Keyエラーが発生。その後Keyエラーについて解消はしたものの。上記のエラーが。。。。

locやインデックス値の指定によってデータの表示をしようとしたのですがうまくいかず。

内容


import csv
import pandas as pd
import seaborn as sns
import matplotlib 
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import japanize_matplotlib

road = pd.read_csv("~~~~.csv",
                   encoding="SHIFT-JIS",
                   keep_default_na=False, # 空欄をNaで置き換えない
                   header=None, # headerは指定しない
                   index_col=[0],
                   engine='python')

road.columns = pd.MultiIndex.from_frame(road.iloc[:11, :].T)
print(road)

dro = road.dropna(how="all")
new = dro.loc[:,["年次(西暦)","地域階層コード","(常住地)東京都"]]
print(new)
sns.pairplot(dro)
plt.savefig("population.png")
plt.show()

解決方法


df = pd.read_csv('/Users/uematsuyuuki/Desktop/ty20rv0800 (1).csv',
                 encoding='shift-jis', 
                 skiprows=11, 
                 usecols=[1,2,6])

read_csvのパラメーターの指定をすることで解決。

なぜか?!

データの中身に問題があった模様。

引数を指定したことによって特定の行をスキップしたことによって解決。

引数skiprows
特定の行をスキップ(除外)して読み込む場合、引数skiprowsを使う。
skiprowsに整数を渡すと、ファイルの先頭をその行数分スキップして読み込む。

population.png

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1