@data_kazu (瑠斗 数原)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

【Python】for文を活用して一つのグラフ内に、複数の折れ線グラフをいれる方法をご教示ください!

■使用言語とライブラリ
・Python
・Google Colaboratory

■本文
現在スポーツジムにて、ユーザーの会員区分別で店舗毎(shop_name)のユーザー数の推移を
matplotlibのplotとfor文を使って、一つのグラフの中にまとめたいと考えております。
こちらに当たって、以下エラーが発生しており、困っております。

※実施手順
0.元データをshop_userという変数にいれたとします。
↓↓イメージ
元データ.jpg

1.元データをフィルタで抽出(今回はナイトタイム会員を例にしてます)

shop_user = shop_user.loc[shop_user["user_type"] == "ナイト会員"]
shop_user

↓↓アウトプットイメージ
フィルタ後.jpg

2.ショップ毎のユーザー推移(月日であるmeasurement_monthごと)をユーザーIDから算出

shop_nightuser_uupivot = shop_user.pivot_table(index = "measurement_month", columns = "store_name", values = "user_id", aggfunc = "count", fill_value = 0)
shop_nightuser_uupivot

↓↓アウトプットイメージ
整形後.jpg

3.横軸をmeasurement_month、縦軸を各store_nameにした折れ線グラフを記載(一つのグラフ内にまとめる)

for i in list(shop_nightuser_uupivot):
  plt.plot(shop_nightuser_uupivot["measurement_month"], shop_nightuser_uupivot[i])
  plt.legend()
  plt.show()

※ここで以下のようなエラーが発生します。

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3360             try:
-> 3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:

4 frames
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'measurement_month'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:
-> 3363                 raise KeyError(key) from err
   3364 
   3365         if is_scalar(key) and isna(key) and not self.hasnans:

KeyError: 'measurement_month'

measurement_monthのKeyErrorとなっておりますが、
measurement_monthはデータフレームを表示しても入っているため、
何が要因でエラーが起きているかが理解できておらず、
こちらなにかおわかりになる方がいらっしゃれば、
ご教示いただけますと幸いです。

※またコードや考え方がそもそも間違っているなども、ご指摘いただけますと幸いです。

恐れ入りますが、よろしくお願いいたします。

0 likes

1Answer

pivotした結果「measurement_month」は列ではなくindexになっているので、df_pivot.indexとして取得する必要があると思います。

df_pivot = df.pivot_table(index = "measurement_month", columns = "store_name", values = "user_id", aggfunc = "count", fill_value = 0)

for col in list(df_pivot):
  plt.plot(df_pivot.index, df_pivot[col], label=col)

plt.legend()
plt.show()

image.png

1Like

Comments

  1. @data_kazu

    Questioner

    ご指摘ありがとうございます!いただいた.indexにしたところ、無事に実行されました!
    大変助かりました!ありがとうございます!

Your answer might help someone💌