Reputation: 1654
I have a pandas dataframe which is a square grid of boolean values with the index and columns being the names of 628 electoral constituencies which have neighbours. e.g.
In[18]: adjacents.index
Out[18]:
Index(['Aberavon', 'Aberconwy', 'Aberdeen North', 'Aberdeen South',
'Aberdeenshire West & Kincardine', 'Airdrie & Shotts', 'Aldershot',
'Aldridge-Brownhills', 'Altrincham & Sale West', 'Alyn & Deeside',
...
'Wrekin, The', 'Wrexham', 'Wycombe', 'Wyre & Preston North',
'Wyre Forest', 'Wythenshawe & Sale East', 'Yeovil', 'York Central',
'York Outer', 'Yorkshire East'],
dtype='object', length=628)
In[19]: adjacents.columns
Out[19]:
Index(['Aberavon', 'Aberconwy', 'Aberdeen North', 'Aberdeen South',
'Aberdeenshire West & Kincardine', 'Airdrie & Shotts', 'Aldershot',
'Aldridge-Brownhills', 'Altrincham & Sale West', 'Alyn & Deeside',
...
'Wrekin, The', 'Wrexham', 'Wycombe', 'Wyre & Preston North',
'Wyre Forest', 'Wythenshawe & Sale East', 'Yeovil', 'York Central',
'York Outer', 'Yorkshire East'],
dtype='object', length=628)
So, Manchester Central constiuency is adjacent to Manchester Gorton, but not Manchester Withington.
In[20]: adjacents['Manchester Central']['Manchester Withington']
Out[20]: False
In[21]: adjacents['Manchester Central']['Manchester Gorton']
Out[21]: True
What's the best way to return the column names for all columns in a row which are True
? (I think it might be something to do with np.argmax()
but can't quite figure it out.)
Upvotes: 0
Views: 80
Reputation: 6766
Well, you could do that, but since your matrix seems to be symmetric you'd be better off finding the row names instead, since this is much simpler:
adjacents[adjacents['Manchester Central']].index
BTW - when accessing an exact location in the table, it is better practice to use loc
:
adjacents.loc['Manchester Central', 'Manchester Gorton']
Upvotes: 1