Reputation: 371
I have a pandas dataframe for graph edges with a multi index as such
df = pd.DataFrame(index=[(1, 2), (2, 3), (3, 4), ...], data=['v1', 'v2', 'v3', ...])
However doing a simple .loc
fails:
df.loc[(1, 2)] # error
df.loc[df.index[0]] # also error
with the message KeyError: 1
. Why does it fail? The index clearly shows that the tuple (1, 2)
is in it and in the docs I see .loc[]
being used similarly.
Edit: Apparently df.loc[[(1, 2)]]
works. Go figure. It was probably interpreting the first iterable as separate keys?
Upvotes: 1
Views: 1546
Reputation: 371
Turns out I needed to wrap the key in another iterable like a list for it to use the whole tuple instead of its elements like so: df.loc[[(1, 2)]]
.
Upvotes: 2