matthiasdenu
matthiasdenu

Reputation: 397

Can I get the string index and column names for a given position in a DataFrame?

Given something like the following

>>> breakfast = pd.DataFrame([[2, 2, 3], 
                              [1, 2, 3], 
                              [3, 0, 2]], 
                             index=['Thuy', 'Kana', 'Malcolm'],
                             columns=['eggs', 'bacon', 'pancakes'])
>>> breakfast
         eggs  bacon  pancakes
Thuy        2      2         3
Kana        1      2         3
Malcolm     3      0         2
>>> breakfast.iloc[1,1]
2

Is it possible to also see that the (row, col) pair for breakfast.iloc[1,1] was ('Kana', 'bacon'). This would be convenient for a large data frame I have that is diagonally symmetric. I am using .iloc to only iterate over one half, but I lose the row and column information in doing so.

Upvotes: 2

Views: 365

Answers (2)

matthiasdenu
matthiasdenu

Reputation: 397

I forgot that the index and columns attributes of the DataFrame are themselves Series. So my solution was breakfast.index[y] or breakfast.columns[x] where y and x are integers. That is how you get the corresponding string for a given location.

Upvotes: 0

EdChum
EdChum

Reputation: 394179

You can just define your own function to return you the index and column label values by ordinal position:

In[96]:
def row_col(index_pos, column_pos):
    return (breakfast.index[index_pos], breakfast.columns[column_pos])
row_col(1,1)

Out[96]: ('Kana', 'bacon')

Upvotes: 1

Related Questions