Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve name of column from its Index in Pandas

I have a pandas dataframe and a numpy array of values of that dataframe. I have the index of a specific column and I already have the row index of an important value. Now I need to get the column name of that particular value from my dataframe.

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

like image 659
Jatin Bhola Avatar asked Mar 28 '17 11:03

Jatin Bhola


People also ask

How do I retrieve column names in Pandas?

To access the names of a Pandas dataframe, we can the method columns(). For example, if our dataframe is called df we just type print(df. columns) to get all the columns of the Pandas dataframe.

Can you name the index column in Pandas?

You can rename (change) column/index names of pandas. DataFrame by using rename() , add_prefix() , add_suffix() , set_axis() methods or updating the columns / index attributes. You can also rename index names (labels) of pandas.

How do you find the index of a column in a DataFrame?

You can get the column index from the column name in Pandas using DataFrame. columns. get_loc() method.

How do I get Pandas index name?

Use pandas. DataFrame. rename_axis() to set the index name/title, in order to get the index use DataFrame.index.name property and the same could be used to set the index name as well.


1 Answers

I think you need index columns names by position (python counts from 0, so for fourth column need 3):

colname = df.columns[pos] 

Sample:

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') 
like image 70
jezrael Avatar answered Sep 21 '22 21:09

jezrael