Python "KeyError: 0" - detect the crossed cells - python

I tried so hard to understand this kind of errors.
Code
#assigne each cell from each site to a dataframe
cell_list = []
grouped = df.groupby(df['Cell Name'])
for i in range(len(df.index)):
if (df['Cell Name'].iloc[i] not in cell_list):
cell_list.append(df['Cell Name'].iloc[i])
for cell in cell_list:
g = grouped.get_group(cell)
for j in range(len(g)-1):
T_vals1 = g[j].values
diff_TCH = T_vals1[1:] - T_vals1[:-1]
T_vals2 = g[j-1].values
diff_TCH2 = T_vals2[1:] - T_vals2[:-1]
print(diff_TCH)
product23 = np.multiply(diff_TCH,diff_TCH2)
print(product23)
Error
This is the error I got:
KeyError Traceback (most recent call
last) ~\anaconda3\lib\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:
~\anaconda3\lib\site-packages\pandas_libs\index.pyx in
pandas._libs.index.IndexEngine.get_loc()
~\anaconda3\lib\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: 0
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call
last)
C:\Users\IMENEP~1\AppData\Local\Temp/ipykernel_6864/4137740194.py in
2 g = grouped.get_group(cell)
3 for j in range(len(g)-1):
----> 4 T_vals1 = g[j].values
5 diff_TCH = T_vals1[1:] - T_vals1[:-1]
6 T_vals2 = g[j-1].values
~\anaconda3\lib\site-packages\pandas\core\frame.py in
getitem(self, key) 3456 if self.columns.nlevels > 1: 3457 return self._getitem_multilevel(key)
-> 3458 indexer = self.columns.get_loc(key) 3459 if is_integer(indexer): 3460 indexer = [indexer]
~\anaconda3\lib\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: 0
Can you help me understand those errors?

Related

KeyError: 0 The above exception was the direct cause of the following exception:

The code was working correctly, but problems appeared in other parts, and when solving the problems of the other parts, this part did not work and I was not able to solve this problem and I hope to find help with you
I am getting an error that in this part:
`
value_result = []
value_skill = []
for i in range(df4.shape[0]):
job_description = df4['job_description'][i]
annotations = skill_extractor.annotate(job_description)
for type_matching, arr_skills in annotations["results"].items():
for skill in arr_skills:
if SKILL_DB[skill["skill_id"]]["skill_name"] in new_stopwords:
value_result.append(SKILL_DB[skill["skill_id"]]["skill_name"])
value_skill.append(SKILL_DB[skill["skill_id"]]["skill_type"])
`
and this is the error message
`
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
3802 try:
-> 3803 return self._engine.get_loc(casted_key)
3804 except KeyError as err:
~\anaconda3\lib\site-packages\pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
~\anaconda3\lib\site-packages\pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
KeyError: 0
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_1268\3053340950.py in <module>
2 value_skill = []
3 for i in range(df4.shape[0]):
----> 4 job_description = df4['job_description'][i]
5 annotations = skill_extractor.annotate(job_description)
6 for type_matching, arr_skills in annotations["results"].items():
~\anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
979
980 elif key_is_scalar:
--> 981 return self._get_value(key)
982
983 if is_hashable(key):
~\anaconda3\lib\site-packages\pandas\core\series.py in _get_value(self, label, takeable)
1087
1088 # Similar to Index.get_value, but we do not fall back to positional
-> 1089 loc = self.index.get_loc(label)
1090 return self.index._get_values_for_loc(self, loc, label)
1091
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
3803 return self._engine.get_loc(casted_key)
3804 except KeyError as err:
-> 3805 raise KeyError(key) from err
3806 except TypeError:
3807 # If we have a listlike key, _check_indexing_error will raise
KeyError: 0
`
i am try to solve but cant do this
Many thanks for your time, much appreciated.

Having issues getting rb.fit() to work for a sentiment analysis project. Python 3.9.12

Getting back into coding after a while of being away.
I'm having issues getting rb.fit() to work for a sentiment analysis project. Python 3.9.12 Also open to other recommendations if you think RandomBaseline is just no good.
rb = RandomBaseline()
#rb.fit(data, target_col)
rb.fit(df_text_analysis, df_text_analysis['Q6'])
I found the code https://asperbrothers.com/blog/sentiment-analysis-in-python/ and it seems I have it setup the same way but I'm getting a KeyError: nan
rb = RandomBaseline()
rb.fit(df.iloc[X_train.index], "Sentiment")
Error output below.
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
File /opt/anaconda3/lib/python3.9/site-packages/pandas/core/indexes/base.py:3621, in Index.get_loc(self, key, method, tolerance)
3620 try:
-> 3621 return self._engine.get_loc(casted_key)
3622 except KeyError as err:
File /opt/anaconda3/lib/python3.9/site-packages/pandas/_libs/index.pyx:136, in pandas._libs.index.IndexEngine.get_loc()
File /opt/anaconda3/lib/python3.9/site-packages/pandas/_libs/index.pyx:163, in pandas._libs.index.IndexEngine.get_loc()
File pandas/_libs/hashtable_class_helper.pxi:5198, in pandas._libs.hashtable.PyObjectHashTable.get_item()
File pandas/_libs/hashtable_class_helper.pxi:5206, in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: nan
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
Input In [12], in <cell line: 3>()
1 rb = RandomBaseline()
2 #rb.fit(data, target_col)
----> 3 rb.fit(df_text_analysis, df_text_analysis['Q6'])
Input In [11], in RandomBaseline.fit(self, data, target_col)
9 agg = data.groupby(target_col).count()
11 for n in feels:
---> 12 self.categories[n] = agg.loc[n][0] / len(data)
File /opt/anaconda3/lib/python3.9/site-packages/pandas/core/indexing.py:967, in _LocationIndexer.__getitem__(self, key)
964 axis = self.axis or 0
966 maybe_callable = com.apply_if_callable(key, self.obj)
--> 967 return self._getitem_axis(maybe_callable, axis=axis)
File /opt/anaconda3/lib/python3.9/site-packages/pandas/core/indexing.py:1202, in _LocIndexer._getitem_axis(self, key, axis)
1200 # fall thru to straight lookup
1201 self._validate_key(key, axis)
-> 1202 return self._get_label(key, axis=axis)
File /opt/anaconda3/lib/python3.9/site-packages/pandas/core/indexing.py:1153, in _LocIndexer._get_label(self, label, axis)
1151 def _get_label(self, label, axis: int):
1152 # GH#5667 this will fail if the label is not present in the axis.
-> 1153 return self.obj.xs(label, axis=axis)
File /opt/anaconda3/lib/python3.9/site-packages/pandas/core/generic.py:3864, in NDFrame.xs(self, key, axis, level, drop_level)
3862 new_index = index[loc]
3863 else:
-> 3864 loc = index.get_loc(key)
3866 if isinstance(loc, np.ndarray):
3867 if loc.dtype == np.bool_:
File /opt/anaconda3/lib/python3.9/site-packages/pandas/core/indexes/base.py:3623, in Index.get_loc(self, key, method, tolerance)
3621 return self._engine.get_loc(casted_key)
3622 except KeyError as err:
-> 3623 raise KeyError(key) from err
3624 except TypeError:
3625 # If we have a listlike key, _check_indexing_error will raise
3626 # InvalidIndexError. Otherwise we fall through and re-raise
3627 # the TypeError.
3628 self._check_indexing_error(key)
KeyError: nan

How can I fix Keyerror: Groups? question about dynamo

when I run dynamo that deals with single-cell RNA seq data.I suffer from a question
dyn.tl.gene_wise_confidence(adata, group= 'group',lineage_dict={'Progenitor':['terminal_cell_state']})
/home/liuyang/anaconda3/envs/dynamo/lib/python3.10/site packages/anndata/_core/anndata.py:1095: FutureWarning: The `inplace` parameter in pandas.Categorical.remove_unused_categories is deprecated and will be removed in a future version.
df_sub[k].cat.remove_unused_categories(inplace=True)
calculating gene velocity vectors confidence based on phase portrait location with priors of progenitor/mature cell types: 0it [00:00, ?it/s]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
File ~/anaconda3/envs/dynamo/lib/python3.10/site-packages/pandas/core/indexes/base.py:3621, in Index.get_loc(self, key, method, tolerance)
3620 try:
3621 return self._engine.get_loc(casted_key)
3622 except KeyError as err:
File ~/anaconda3/envs/dynamo/lib/python3.10/site-packages/pandas/_libs/index.pyx:136, in pandas._libs.index.IndexEngine.get_loc()
File ~/anaconda3/envs/dynamo/lib/python3.10/site-packages/pandas/_libs/index.pyx:163, in pandas._libs.index.IndexEngine.get_loc()
File pandas/_libs/hashtable_class_helper.pxi:5198, in pandas._libs.hashtable.PyObjectHashTable.get_item()
File pandas/_libs/hashtable_class_helper.pxi:5206, in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'group'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
Input In [14], in <cell line: 1>()
----> 1 dyn.tl.gene_wise_confidence(adata, group= 'group',lineage_dict={'Progenitor': ['terminal_cell_state']})
File ~/.local/lib/python3.10/site-packages/dynamo/tools/metric_velocity.py:352, in gene_wise_confidence(adata, group, lineage_dict, genes, ekey, vkey, X_data, V_data, V_threshold)
349 mature_cells_groups = [mature_cells_groups]
351 for i, progenitor in enumerate(progenitors_groups):
352 prog_vals = all_vals[adata.obs[group] == progenitor]
353 prog_vals_v = all_vals_v[adata.obs[group] == progenitor]
354 if len(prog_vals_v) == 0:
File ~/anaconda3/envs/dynamo/lib/python3.10/site-packages/pandas/core/frame.py:3505, in DataFrame.__getitem__(self, key)
3503 if self.columns.nlevels > 1:
3504 return self._getitem_multilevel(key)
3505 indexer = self.columns.get_loc(key)
3506 if is_integer(indexer):
3507 indexer = [indexer]
File ~/anaconda3/envs/dynamo/lib/python3.10/site-packages/pandas/core/indexes/base.py:3623, in Index.get_loc(self, key, method, tolerance)
3621 return self._engine.get_loc(casted_key)
3622 except KeyError as err:
3623 raise KeyError(key) from err
3624 except TypeError:
3625 # If we have a listlike key, _check_indexing_error will raise
3626 # InvalidIndexError. Otherwise we fall through and re-raise
3627 # the TypeError.
3628 self._check_indexing_error(key)
KeyError: 'group'
But, I do it all follow the "10 minutes to dynamo", how can I fix it ? does someone had suffer from this kind of question?
​

Pandas df: retrieving the records that have cell value == float not working. What am I doing wrong?

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
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.

i'm a new learner in jupyter and don't understand this error, i'm looking to remove the $ sign

MKT['Income'] = MKT['Income'].str.replace('$', '')
i get this error [enter image description here][1]
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2894 try:
-> 2895 return self._engine.get_loc(casted_key)
2896 except KeyError as err:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
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: 'Income'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
<ipython-input-22-5ea6ddc03a8c> in <module>
----> 1 MKT['Income'] = MKT['Income'].str.replace('$', '')
~\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
2900 if self.columns.nlevels > 1:
2901 return self._getitem_multilevel(key)
-> 2902 indexer = self.columns.get_loc(key)
2903 if is_integer(indexer):
2904 indexer = [indexer]
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2895 return self._engine.get_loc(casted_key)
2896 except KeyError as err:
-> 2897 raise KeyError(key) from err
2898
2899 if tolerance is not None:
KeyError: 'Income'
[1]: https://i.stack.imgur.com/5WszY.png

Categories

Resources