実現したいこと
Python実践データ分析100本ノック第二章ノック20にて、
売り上げデータ(import_data)を縦に購買月、横に顧客名を並べてpivotする練習問題がある
そこで本書の記載内容からは逸脱するが、
pivot_tableメソッドの引数に"margins=True"を追加して合計行を加えたい
発生している問題・分からないこと
そもそもエラーが表示される
エラーメッセージ
error
1KeyError Traceback (most recent call last) 2/usr/local/lib/python3.11/dist-packages/pandas/core/indexes/base.py in get_loc(self, key) 3 3804 try: 4-> 3805 return self._engine.get_loc(casted_key) 5 3806 except KeyError as err: 6 7index.pyx in pandas._libs.index.IndexEngine.get_loc() 8 9index.pyx in pandas._libs.index.IndexEngine.get_loc() 10 11pandas/_libs/index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type() 12 13KeyError: 'さだ千佳子' 14 15The above exception was the direct cause of the following exception: 16 17KeyError Traceback (most recent call last) 188 frames 19/usr/local/lib/python3.11/dist-packages/pandas/core/indexes/base.py in get_loc(self, key) 20 3810 ): 21 3811 raise InvalidIndexError(key) 22-> 3812 raise KeyError(key) from err 23 3813 except TypeError: 24 3814 # If we have a listlike key, _check_indexing_error will raise 25 26KeyError: 'さだ千佳子'
該当のソースコード
python
1byCutomer = import_data.pivot_table(index="purchase_month",columns="顧客名",aggfunc="size",fill_value=0,margins=True) 2byCutomer
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
Geminiに聞いてみたが、'さだ千佳子'が存在するかを確認してくださいと言われた
print(import_data["顧客名"].isin(['さだ千佳子']).any())でTrueとなるため、存在はしていることがわかっている
補足
特になし

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2025/02/10 05:25
2025/02/10 05:46
2025/02/10 07:28