質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

1回答

4536閲覧

pythonのpandasでまとめたデータをグラフにする際に列を指定するところでKeyErrorが起こる

nemaki

総合スコア11

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2019/05/02 17:14

前提・実現したいこと・問題になっていること

実験データをpandasでまとめて、matplotlibでグラフ化することをしたいです。

1つのデータファイルには5つの異なる種類のデータがあるので、それぞれfrList,...,angleListのように名前を付けています。パラメータ別にデータファイルが複数あるので、1つでdataframeにまとめる際にmulticolumにしてどのパラメータのデータたちなのかをわかるようにしてます。

plotする際に「どのパラメータのどのデータ」なのかを指定して2次元のグラフにしたいのですが、その際にKeyError:'[]' not in index となってしまいます([]には数値データがカンマ区切りで600個入っているのですが、文字数制限のため~にしてます、下のエラーメッセージも同じです)。

いくつか該当しそうなキーワードでググってみたのですが、それらしいのを見つけられませんでした。

解決できそうな方がいらっしゃいましたら、よろしくお願いします。

該当のソースコード

python3

1List_att_10_tmp_57 = pd.read_csv("att_10-tmp_5684.dat", sep='\s+') 2List_att_10_tmp_57.columns=['frList_57', 'IList_57','QList_57','dBList_57','angleList_57'] 3 4List_att_10_tmp_74 = pd.read_csv("att_10-tmp_7446.dat", sep='\s+') 5List_att_10_tmp_74.columns=['frList_74', 'IList_74','QList_74','dBList_74','angleList_74'] 6 7testList = pd.concat([List_att_10_tmp_57,List_att_10_tmp_74],axis=1,keys=['tmp_57', 'tmp_74']) 8 9testList.plot.scatter(x=testList.loc[:,pd.IndexSlice['tmp_57','frList_57']], y=testList.loc[:,pd.IndexSlice['tmp_74','dBList_74']])

発生している問題・エラーメッセージ

KeyError Traceback (most recent call last) <ipython-input-24-89ba11219a69> in <module> 9 testList = pd.concat([List_att_10_tmp_57,List_att_10_tmp_74],axis=1,keys=['tmp_57', 'tmp_74']) 10 ---> 11 testList.plot.scatter(x=testList.loc[:,pd.IndexSlice['tmp_57','frList_57']], y=testList.loc[:,pd.IndexSlice['tmp_74','dBList_74']]) ~/anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py in scatter(self, x, y, s, c, **kwds) 3514 ... colormap='viridis') 3515 """ -> 3516 return self(kind='scatter', x=x, y=y, c=c, s=s, **kwds) 3517 3518 def hexbin(self, x, y, C=None, reduce_C_function=None, gridsize=None, ~/anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py in __call__(self, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds) 2940 fontsize=fontsize, colormap=colormap, table=table, 2941 yerr=yerr, xerr=xerr, secondary_y=secondary_y, -> 2942 sort_columns=sort_columns, **kwds) 2943 __call__.__doc__ = plot_frame.__doc__ 2944 ~/anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py in plot_frame(data, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds) 1971 yerr=yerr, xerr=xerr, 1972 secondary_y=secondary_y, sort_columns=sort_columns, -> 1973 **kwds) 1974 1975 ~/anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py in _plot(data, x, y, subplots, ax, kind, **kwds) 1738 if isinstance(data, ABCDataFrame): 1739 plot_obj = klass(data, x=x, y=y, subplots=subplots, ax=ax, -> 1740 kind=kind, **kwds) 1741 else: 1742 raise ValueError("plot kind %r can only be used for data frames" ~/anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py in __init__(self, data, x, y, s, c, **kwargs) 858 # the handling of this argument later 859 s = 20 --> 860 super(ScatterPlot, self).__init__(data, x, y, s=s, **kwargs) 861 if is_integer(c) and not self.data.columns.holds_integer(): 862 c = self.data.columns[c] ~/anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py in __init__(self, data, x, y, **kwargs) 801 if is_integer(y) and not self.data.columns.holds_integer(): 802 y = self.data.columns[y] --> 803 if len(self.data[x]._get_numeric_data()) == 0: 804 raise ValueError(self._kind + ' requires x column to be numeric') 805 if len(self.data[y]._get_numeric_data()) == 0: ~/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py in __getitem__(self, key) 2932 key = list(key) 2933 indexer = self.loc._convert_to_indexer(key, axis=1, -> 2934 raise_missing=True) 2935 2936 # take() does not accept boolean indexers ~/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py in _convert_to_indexer(self, obj, axis, is_setter, raise_missing) 1352 kwargs = {'raise_missing': True if is_setter else 1353 raise_missing} -> 1354 return self._get_listlike_indexer(obj, axis, **kwargs)[1] 1355 else: 1356 try: ~/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py in _get_listlike_indexer(self, key, axis, raise_missing) 1140 # if it cannot handle: 1141 indexer, keyarr = ax._convert_listlike_indexer(key, -> 1142 kind=self.name) 1143 # We only act on all found values: 1144 if indexer is not None and (indexer != -1).all(): ~/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/multi.py in _convert_listlike_indexer(self, keyarr, kind) 2134 mask = check == -1 2135 if mask.any(): -> 2136 raise KeyError('%s not in index' % keyarr[mask]) 2137 2138 return indexer, keyarr KeyError: '[~] not in index'

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

x : int or str
The column name or column position to be used as horizontal coordinates for each point.

y : int or str
The column name or column position to be used as vertical coordinates for each point.

pandas.DataFrame.plot.scatter — pandas 0.24.2 documentation

という仕様ですので、そういうものをxyに渡さないといけないのです。

方法1

multicolumにしちゃうとむずい(というかたぶんできないはず)ので、普通のカラムで表現することにします。

python

1List_att_10_tmp_57 = pd.read_csv("att_10-tmp_5684.dat", sep='\s+') 2List_att_10_tmp_57.columns=['frList_57', 'IList_57','QList_57','dBList_57','angleList_57'] 3 4List_att_10_tmp_74 = pd.read_csv("att_10-tmp_7446.dat", sep='\s+') 5List_att_10_tmp_74.columns=['frList_74', 'IList_74','QList_74','dBList_74','angleList_74'] 6 7testList = pd.concat([List_att_10_tmp_57,List_att_10_tmp_74],axis=1)

あとは普通にできるはずです。

python

1testList.plot.scatter(x="frList_57", y="dBList_74") 2
方法2

pandasのscatterにこだわらないで、matplotlibのscatterを使うという手があります。データをちゃんと取り出せていればこちらでも良いと思います。

matplotlib.pyplot.scatter — Matplotlib 3.0.3 documentation

投稿2019/05/02 18:18

hayataka2049

総合スコア30933

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

nemaki

2019/05/03 07:41

回答していただきありがとうございます。 提示していただいた方法2でしたいことができました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問