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

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

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

MatplotlibはPythonのおよび、NumPy用のグラフ描画ライブラリです。多くの場合、IPythonと連携して使われます。

NumPy

NumPyはPythonのプログラミング言語の科学的と数学的なコンピューティングに関する拡張モジュールです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

pandas

Pandasは、PythonでRにおけるデータフレームに似た型を持たせることができるライブラリです。 行列計算の負担が大幅に軽減されるため、Rで行っていた集計作業をPythonでも比較的簡単に行えます。 データ構造を変更したりデータ分析したりするときにも便利です。

Q&A

解決済

1回答

2064閲覧

pandasデータフレームのseaborn pairplotについて

chgrios

総合スコア70

Matplotlib

MatplotlibはPythonのおよび、NumPy用のグラフ描画ライブラリです。多くの場合、IPythonと連携して使われます。

NumPy

NumPyはPythonのプログラミング言語の科学的と数学的なコンピューティングに関する拡張モジュールです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

pandas

Pandasは、PythonでRにおけるデータフレームに似た型を持たせることができるライブラリです。 行列計算の負担が大幅に軽減されるため、Rで行っていた集計作業をPythonでも比較的簡単に行えます。 データ構造を変更したりデータ分析したりするときにも便利です。

0グッド

1クリップ

投稿2019/08/16 02:20

編集2019/08/16 06:26

下のような(7,3)の行列があります。(数学国語英語の成績を想定)

python

1import pandas as pd 2import seaborn as sns 3from sklearn.cluster import KMeans 4 5features = np.array([ 6 [ 80, 85, 100 ], 7 [ 96, 100, 100 ], 8 [ 54, 83, 98 ], 9 [ 80, 98, 98 ], 10 [ 90, 92, 91 ], 11 [ 84, 78, 82 ], 12 [ 79, 100, 96 ], 13 ]) 14

これをkmeansでクラスタリングしてラベルごとにseabornのpairplotで出力したいのですが、

python

1df =pd.DataFrame(features, columns=['a','b','c']) 2model = KMeans(n_clusters=4) 3model.fit(features) 4labels = model.labels_ 5labels_df = pd.DataFrame(labels, columns =['label']) 6df_concat = pd.concat([df, labels_df], axis=1) 7df_concat['label'] = df_concat['label'].astype(str) 8 9sns.pairplot(df_concat, hue='label',diag_kind='kde') 10
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) /usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 2889 try: -> 2890 return self._engine.get_loc(key) 2891 except KeyError: pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() 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: 'label' During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last) <ipython-input-134-0c6750a0a143> in <module> 56 # colors = [color_codes[x] for x in labels] 57 # plotting.scatter_matrix(df) ---> 58 sns.pairplot(df_concat.iloc[:,:3], hue='label',diag_kind='kde') 59 60 #put labels aside /usr/local/lib/python3.6/dist-packages/seaborn/axisgrid.py in pairplot(data, hue, hue_order, palette, vars, x_vars, y_vars, kind, diag_kind, markers, height, aspect, dropna, plot_kws, diag_kws, grid_kws, size) 2082 hue_order=hue_order, palette=palette, 2083 diag_sharey=diag_sharey, -> 2084 height=height, aspect=aspect, dropna=dropna, **grid_kws) 2085 2086 # Add the markers here as PairGrid has figured out how many levels of the /usr/local/lib/python3.6/dist-packages/seaborn/axisgrid.py in __init__(self, data, hue, hue_order, palette, hue_kws, vars, x_vars, y_vars, diag_sharey, height, aspect, despine, dropna, size) 1288 index=data.index) 1289 else: -> 1290 hue_names = utils.categorical_order(data[hue], hue_order) 1291 if dropna: 1292 # Filter NA from the list of unique hue names /usr/local/lib/python3.6/dist-packages/pandas/core/frame.py in __getitem__(self, key) 2973 if self.columns.nlevels > 1: 2974 return self._getitem_multilevel(key) -> 2975 indexer = self.columns.get_loc(key) 2976 if is_integer(indexer): 2977 indexer = [indexer] /usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 2890 return self._engine.get_loc(key) 2891 except KeyError: -> 2892 return self._engine.get_loc(self._maybe_cast_indexer(key)) 2893 indexer = self.get_indexer([key], method=method, tolerance=tolerance) 2894 if indexer.ndim > 1 or indexer.size > 1: pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() 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: 'label'

ここでhue='label'にするとエラーがでてしまいます。labelのデータタイプはオブジェクトのはずなのですが、、、
どうすればよいのでしょうか。

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

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

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

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

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

can110

2019/08/16 03:13

エラー内容を記載ください。 また、import文などは省略せず、第三者がそのまま実行、検証できるコードを提示すると回答得られやすいです。
can110

2019/08/16 03:53

提示ソースとエラー発生時のソースが異なっているようですが、どちらが正しいでしょうか?
meg_

2019/08/16 04:04

「import andas as pd」は「import pandas as pd」ですか? 「from sklearn import KMeans」は当方ではエラーになります。
meg_

2019/08/16 04:05

「np」のimport分も追記お願いします。
guest

回答1

0

ベストアンサー

試したところ、問題なく実行出来ました。
掲載のコードに不足があるため、当方にて手入力したため全く同じコードではありません。
(Windows8、Python3.6.4(Anaconda))

下記は実行結果を保存したものです。

イメージ説明

【追記】

Python

1import pandas as pd 2import seaborn as sns 3from sklearn.cluster import KMeans 4import numpy as np 5 6features = np.array([ 7 [ 80, 85, 100 ], 8 [ 96, 100, 100 ], 9 [ 54, 83, 98 ], 10 [ 80, 98, 98 ], 11 [ 90, 92, 91 ], 12 [ 84, 78, 82 ], 13 [ 79, 100, 96 ], 14 ]) 15 16df = pd.DataFrame(features, columns=['a', 'b', 'c']) 17model = KMeans(n_clusters=4) 18model.fit(features) 19labels = model.labels_ 20labels_df = pd.DataFrame(labels, columns=['label']) 21df_concat = pd.concat([df, labels_df], axis=1) 22df_concat['label'].astype(str) 23pg = sns.pairplot(df_concat, hue='label', diag_kind='kde') 24pg.savefig('') #ファイルパス

投稿2019/08/16 04:20

編集2019/08/16 06:13
meg_

総合スコア10577

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

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

chgrios

2019/08/16 04:58

上記のモジュールを修正してもエラーが起こってしまいました。コードをコピペしていただけないでしょうか?
meg_

2019/08/16 05:15

載せるのは良いのですが、質問のコードの修正もお願いします。
chgrios

2019/08/16 06:25

ValueError: `dataset` input should have multiple elements.このようなエラーがでませんか?修正しました。
meg_

2019/08/16 06:31

私の環境では「pg = sns.pairplot(df_concat, hue='label', diag_kind='kde')」のところでWarningは沢山でますが、エラーは出ません。 DataFrameがどうなっているかデバッグしたら良いかと思います。
m3yrin

2019/08/17 04:11

追記していただいたコードについて、手元の環境で少し試してみました。 環境はMac 10.14.6 / Python 3.6.9, Python 3.7.4、seabornは0.9.0です。 conda経由でseabornをインストールした場合には「pg = sns.pairplot(df_concat, hue='label', diag_kind='kde')」箇所にて RuntimeWarning: が4つほど発生しましたが、meg_様の投稿の通り、画像は生成されました。 pip経由でseabornをインストールした場合には「pg = sns.pairplot(df_concat, hue='label', diag_kind='kde')」の箇所にて、ValueError: `dataset` input should have multiple elements. のエラーが再現できました。 pip経由でインストールしたseabornをpip uninstallでアンインストールし、conda経由で再インストールすると、ValueErrorは発生せず画像が生成されました。 ValueErrorについては下記で議論があり、kdeの計算の問題のようです。 https://github.com/mwaskom/seaborn/issues/1627 解決策としては * conda経由でseabornを再インストールする * github issueの議論のとおり、`diag_kind='hist'`を指定する が考えられます。 以上です。
chgrios

2019/08/17 08:48

親切な解答ありがとうございました。解決しました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問