How to use loc[] In python
Question:
For the following dataframe:
d = {'a':[10,11,12,13],'b':[20,21,22,23], 'c':[30,31,32,33]}
pd_df = pd.DataFrame(d)
pd_df.set_index('a')
b c
a
10 20 30
11 21 31
12 22 32
13 23 33
This code
pd_df.loc[10]
gives the following error:
~/.local/lib/python3.6/site-packages/pandas/core/indexing.py in _validate_key(self, key, axis)
1789 if not ax.contains(key):
-> 1790 error()
1791 except TypeError as e:
~/.local/lib/python3.6/site-packages/pandas/core/indexing.py in error()
1784 .format(key=key,
-> 1785 axis=self.obj._get_axis_name(axis)))
1786
KeyError: 'the label [10] is not in the [index]'
How can I fix it?
Answers:
If you want to set index to a
, then do the following:
d = {'a':[10,11,12,13],'b':[20,21,22,23], 'c':[30,31,32,33]}
pd_df = pd.DataFrame(d)
pd_df = pd_df.set_index('a') ## <<< CHANGE HERE
Then
pd_df.loc[10]
Output:
b 20
c 30
Name: 10, dtype: int64
I recommend to use iloc since you’re filtering by index.
For the following dataframe:
d = {'a':[10,11,12,13],'b':[20,21,22,23], 'c':[30,31,32,33]}
pd_df = pd.DataFrame(d)
pd_df.set_index('a')
b c
a
10 20 30
11 21 31
12 22 32
13 23 33
This code
pd_df.loc[10]
gives the following error:
~/.local/lib/python3.6/site-packages/pandas/core/indexing.py in _validate_key(self, key, axis)
1789 if not ax.contains(key):
-> 1790 error()
1791 except TypeError as e:
~/.local/lib/python3.6/site-packages/pandas/core/indexing.py in error()
1784 .format(key=key,
-> 1785 axis=self.obj._get_axis_name(axis)))
1786
KeyError: 'the label [10] is not in the [index]'
How can I fix it?
If you want to set index to a
, then do the following:
d = {'a':[10,11,12,13],'b':[20,21,22,23], 'c':[30,31,32,33]}
pd_df = pd.DataFrame(d)
pd_df = pd_df.set_index('a') ## <<< CHANGE HERE
Then
pd_df.loc[10]
Output:
b 20
c 30
Name: 10, dtype: int64
I recommend to use iloc since you’re filtering by index.