2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pandas 抽出基礎文法 / レスポンスを matplotlib に適用

Last updated at Posted at 2020-01-18

OverView

Pandas で各集計結果を取得する際の指定について、基本的な用法をまとめる。
以下、data をDataFrameオブジェクトとする。

基本編

指定インデックスの行を取得

data[<index>]

# インデックス1の行を取得する
# (インデックスは0始まりなので、2行目となる)
data[1]

指定カラム名の列を取得

data[<column_name>]

# カラム名'name'の列を取得する
data['name']

条件を満たす行のみを取得

data[<インデックス単位のboolean>]

インデックス単位のbooleanイメージは以下。
こちらの例だと、インデックス0,2の行のみを抽出する。

0     True
1    False
2     True
3    False

インデックス単位boolean生成例は以下。Pythonの判定式もそのまま使える。

# ageカラムの値が20以上
data['age'] >= 20

# nameカラムが'郎’の文字を含む
data['name'].str.contains('')

# nameカラムが重複していない
data[~data['name'].duplicated()]

応用編

基本編最後で扱った「条件を満たす行のみを取得」をベースに、色々なレスポンスフォーマットを出力してみる.

ここで、data に格納されている統計データは、以下とする。

index height class grade weight
0 178.820262 a 2 65.649452
1 172.000786 b 5 55.956723
2 179.337790 a 4 56.480630
3 181.204466 b 1 62.908190
4 169.483906 a 4 65.768826
5 174.893690 b 4 56.188545

条件を満たす行のみを取得

まずは基本編のおさらい。

data[data['class'] == 'a']

       height class grade weight
0   178.820262   a   2  65.649452
2   179.337790   a   4  56.480630
4   169.483906   a   4  65.768826

条件を満たす行の各値をリスト形式で取得

.values を実行することで、1レコードの各値を1リストとし、それをレコードごとに要素にもつ2重リストを取得する。

data[data['class'] == 'a'].values

[[178.8202617298383 'a' 2 65.64945209116877]
 [179.33778995074982 'a' 4 56.48062978465752]
 [169.4839057410322 'a' 4 65.76882607944115]]

条件を満たす行のインデックスとカラム値を取得

.locを実行し、インデックスと指定したカラム値を取得する。
この形式は、matplotlib の plot に渡せる形式になる。

data.loc[data['class'] == 'a', 'height']

0     178.820262
2     179.337790
4     169.483906

# args を使って plot 描写
args = data.loc[data['class'] == 'a', 'height']
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(args)
plt.show()

image.png

指定条件を満たす行のカラム値のみをリスト形式で取得

.loc した結果を .values すると、指定カラム値のみをリスト形式で取得できる。
こちらは、 matplotlib の hist で利用できる。

data.loc[data['class'] == 'a', '身長'].values

[178.82026173 179.33778995 169.48390574]

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.hist(data.loc[data['クラス'] == 'a', '身長'].values)
plt.show()

image.png

レコード数が増えれば、もっと映えるグラフになります!

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?