cristian hantig
cristian hantig

Reputation: 1320

How to select multiple cell from a pandas DataFrame?

I have the following dataframe:

a = pd.DataFrame({'a': {0: 2, 1:3, 2: 5},'b': {0: 5, 1:3, 2:6}, 'c': {0: 2, 1:1, 2:2}})
a
OUT:
    a   b   c
0   2   5   2
1   7   3   1
2   5   6   2

and i have the following positions:

index_coords = [0, 1]
columns_coords = ['b', 'b']

I would like to get:

b  0    5
b  1    3

I used the following:

a.unstack(-1).loc[[(col, row) for col, row in zip(columns_coords, index_coords)]]
b  0    5
b  1    3

I'm interested in a more straight forward method, something like(if exists):

a.get_by_coords(index_coords, columns_coords)

I want to find out if there exists any.

Upvotes: 1

Views: 782

Answers (2)

BENY
BENY

Reputation: 323316

You can use stack with reindex + swaplevel:

a.stack().reindex(pd.MultiIndex.from_arrays([index_coords,columns_coords])).swaplevel(i=0,j=1)
b  0    5
   1    3
dtype: int64

Upvotes: 1

jezrael
jezrael

Reputation: 863156

I think not exist in npandas, your solution is nice. Also should be simplier:

print (a.unstack(-1).loc[list(zip(columns_coords, index_coords))])
b  0    5
   1    3
dtype: int64

Close what you need is select by MultiIndex.from_arrays:

#swapped columns, index lists
mux = pd.MultiIndex.from_arrays([columns_coords,index_coords])
print (a.unstack(-1).loc[mux])
b  0    5
   1    3
dtype: int64

Upvotes: 1

Related Questions