Table of Contents
問題
Pandas で CSV を読み込みたくて次のコードを実行したところ…
import pandas as pd
df = pd.read_csv('bmi.csv')label = df['label']print(label)
以下のエラーが出ました。
> Traceback (most recent call last):>> File "C:\Users\user\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3063, in get_loc>> return self.\_engine.get_loc(key)>> File "pandas\\\_libs\index.pyx", line 140, in pandas.\_libs.index.IndexEngine.get_loc>> File "pandas\\\_libs\index.pyx", line 162, in pandas.\_libs.index.IndexEngine.get_loc>> File "pandas\\\_libs\hashtable_class_helper.pxi", line 1492, in pandas.\_libs.hashtable.PyObjectHashTable.get_item>> File "pandas\\\_libs\hashtable_class_helper.pxi", line 1500, in pandas.\_libs.hashtable.PyObjectHashTable.get_item>> KeyError: 'label'>> During handling of the above exception, another exception occurred:>> Traceback (most recent call last):>> File "C:/Users/user/PycharmProjects/kujirabon/practice/bmi-test.py", line 10, in>> label = tbl['label']>> File "C:\Users\user\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2685, in \_\_getitem\_\_>> return self.\_getitem_column(key)>> File "C:\Users\user\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2692, in \_getitem_column>> return self.\_get_item_cache(key)>> File "C:\Users\user\Anaconda3\lib\site-packages\pandas\core\generic.py", line 2486, in \_get_item_cache>> values = self.\_data.get(item)>> File "C:\Users\user\Anaconda3\lib\site-packages\pandas\core\internals.py", line 4115, in get>> loc = self.items.get_loc(item)>> File "C:\Users\user\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3065, in get_loc>> return self.\_engine.get_loc(self.\_maybe_cast_indexer(key))>> File "pandas\\\_libs\index.pyx", line 140, in pandas.\_libs.index.IndexEngine.get_loc>> File "pandas\\\_libs\index.pyx", line 162, in pandas.\_libs.index.IndexEngine.get_loc>> File "pandas\\\_libs\hashtable_class_helper.pxi", line 1492, in pandas.\_libs.hashtable.PyObjectHashTable.get_item>> File "pandas\\\_libs\hashtable_class_helper.pxi", line 1500, in pandas.\_libs.hashtable.PyObjectHashTable.get_item>> KeyError: 'label'
bmi.csvの中身
height | weight | label |
---|---|---|
180 | 80 | normal |
172 | 65 | normal |
解決方法
どうしたものかと思って色々ググっていたところ、同じ問題が StackOverflow にありました。
python - Problems while trying to read a csv with pandas? - Stack Overflow
これによると CSV のヘッダーが、weight, height, label となっているとき、label を指定したければ、,の後ろの半角スペースまで入れる必要があるということでした。
つまり、label を指定したければ、df['label']
と記述する必要があるということです。
また、別の解法として、read_csv
するときにオプションでskipinitialspace=True
を追加してあげれば df['label']
としても問題ありませんでした。