The average person is using DataFrame and wants a specific column or index name! Don't you think? I think well.
It's officially an API, so I think it's a bad idea, I want it. A specific column name or index name!
Well, I don't think anyone wrote it because it's probably too easy.
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)
So, this model is completed.
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 |
This time, as a demo I would like to get the index name and column name for which df == 12.
df12 = df[df == 12]
Then
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 |
It can be obtained.
Using this mechanism,
df12.columns[df12[df == 12].any()]
If so, the column name,
Index(['c'], dtype='object')
It can be obtained.
This will be the relevant column name.
So how do you get the index name? If you think normally
df12.index[df12[df == 12].any()]
It seems that you can get it at.
However, this strategy does not work.
df12[df == 12].any()
As you can see by running
df12[df == 12].any() == 'c' (Column name)
Because it has become.
So
df12.index[df12[df == 12].any()]
The result of
Index(['c'], dtype='object')
It will be.
I was in trouble.
However, transposition is convenient at such times!
df12.index[df12[df == 12].T.any()]
It is a solution.
Since the column name can be obtained with df12 [df == 12] .any ()
,
All you have to do is transpose the Index name to the column name.
With this, the goal is achieved. I'm happy.
Recommended Posts