I have this code and I can't figure out what to do to retrieve the row that I want.
I am trying to retrieve the row that has device_id=16384035
. I tried both float and integer and also string there (since it tells me the column is object) but none worked
print(s_devices['Device ID'])
print(s_devices.columns)
print(s_devices.iloc[0,1])
print(type(s_devices.iloc[0,1]))
print(s_devices[['Device ID']==float(16384035)])
The above prints the below
0 16384035.0
1 17177488.0
2 16384036.0
3 17177489.0
4 0
...
534 17746358.0
535 17746359.0
536 17746360.0
537 17746361.0
538 17746362.0
Name: Device ID, Length: 539, dtype: object
Index(['Serial Number', 'Device ID', 'Device Name'.....some keys removed from here],
dtype='object')
16384035.0
<class 'float'>
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~/.local/lib/python3.9/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
3360 try:
-> 3361 return self._engine.get_loc(casted_key)
3362 except KeyError as err:
~/.local/lib/python3.9/site-packages/pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
~/.local/lib/python3.9/site-packages/pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: False
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
/tmp/ipykernel_540/2993650396.py in <module>
3 print(s_devices.iloc[0,1])
4 print(type(s_devices.iloc[0,1]))
----> 5 print(s_devices[['Device ID']==float(16384035)])
~/.local/lib/python3.9/site-packages/pandas/core/frame.py in __getitem__(self, key)
3453 if self.columns.nlevels > 1:
3454 return self._getitem_multilevel(key)
-> 3455 indexer = self.columns.get_loc(key)
3456 if is_integer(indexer):
3457 indexer = [indexer]
~/.local/lib/python3.9/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
3361 return self._engine.get_loc(casted_key)
3362 except KeyError as err:
-> 3363 raise KeyError(key) from err
3364
3365 if is_scalar(key) and isna(key) and not self.hasnans:
KeyError: False
CodePudding user response:
You're indexing it wrong:
s_devices[['Device ID']==float(16384035)]
You create a boolean Series with the equality and index the DataFrame with it:
msk = s_devices['Device ID']==float(16384035)
out = s_devices[msk]
or as a one-liner:
out = s_devices[s_devices['Device ID']==float(16384035)]
Note that ['Device ID']==float(16384035)
evaluates to False. So what you're trying to do is: s_devices[False]
which raises the KeyError since there's no column named False
.