13
11

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 DataFrame で、特定のカラム名、インデックス名を取得する方法

Posted at

カラム名が欲しい!

普通の人は、DataFrame を使っていて、特定のカラム名やインデックス名が欲しい!と思わないんですかね?
僕は、良く思います。

公式にAPI がなさげなので、たぶん邪道だと思いますが、
僕は、欲しいんです。
特定のカラム名やインデックス名が!

まあ、たぶん簡単すぎるからだれも書いてないんだと思いますけど。

サンプルコード

カラム名を取得

import pandas as pd
import numpy as np
a = np.array([i for i in range(100)]).reshape(10, 10)
c = 'abcdefghij'
d = 'klmnopqrst'
columns = [i for i in c]
index = [i for i in d]
df = pd.DataFrame(a, columns=columns, index=index)

で、今回のひな型が完成しました。

a b c d e f g h i j
k 0 1 2 3 4 5 6 7 8 9
l 10 11 12 13 14 15 16 17 18 19
m 20 21 22 23 24 25 26 27 28 29
n 30 31 32 33 34 35 36 37 38 39
o 40 41 42 43 44 45 46 47 48 49
p 50 51 52 53 54 55 56 57 58 59
q 60 61 62 63 64 65 66 67 68 69
r 70 71 72 73 74 75 76 77 78 79
s 80 81 82 83 84 85 86 87 88 89
t 90 91 92 93 94 95 96 97 98 99

今回は、デモとして、
df == 12 となるインデックス名、カラム名を取得したいと思います。

df12 = df[df == 12]

とすると、

a b c d e f g h i j
k NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
l NaN NaN 12.0 NaN NaN NaN NaN NaN NaN NaN
m NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
n NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
o NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
p NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
q NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
r NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
s NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
t NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

が得られます。

この機構を使って、

df12.columns[df12[df == 12].any()]

とすれば、カラム名、

Index(['c'], dtype='object')

が得られます。

これが、該当するカラム名になります。

インデックス名を取得

では、インデックス名の取得はどのようにすればよいのでしょうか?
普通に考えたら、

df12.index[df12[df == 12].any()]

で取得できそうです。

しかし、この作戦はうまくいきません。

df12[df == 12].any()

を実行してみるとわかりますが、

df12[df == 12].any() == 'c' (カラム名)

となってしまっているからです。

なので、

df12.index[df12[df == 12].any()]

の結果も

Index(['c'], dtype='object')

となってしまします。

困った。

が、こんな時こそ便利なのが、転置!

df12.index[df12[df == 12].T.any()]

で解決です。
df12[df == 12].any() でカラム名が取得できるので、
Index 名をカラム名にすべく転置してあげればよいのです。

これにて、目標達成。
めでたしめでたし。

13
11
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
13
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?