Get column name from its index in Pandas

I have a pandas framework and an array of numpy values ​​for this data frame. I have the index of a specific column, and I already have the index of the row of importance. Now I need to get the column name of this particular value from my frame.

After searching for the documents, I found out that I can do the opposite, but not what I want.

+6
source share
1 answer

I think you need the column names of the indexes by position (the number of python from 0, so for the fourth column you need 3):

colname = df.columns[pos]

Example:

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df)
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

pos = 3
colname = df.columns[pos]
print (colname)
D

pos = [3,5]
colname = df.columns[pos]
print (colname)
Index(['D', 'F'], dtype='object')
+6
source

Source: https://habr.com/ru/post/1016107/


All Articles