Screen Link: Learn data science with Python and R projects
My Code:
import pandas as pd
laptops = pd.read_csv('laptops.csv', encoding='Latin-1')
def clean_w(weight):
laptops["weight"] = laptops["weight"].str.replace("kg","").astype(float)
laptops["weight"] = laptops["weight"].str.replace("kgs","").astype(float)
return weight
new_weight = []
for row in laptops["weight"].unique():
clean_weight = clean_w(row)
new_weight.append(clean_weight)
weight_update = new_weight
laptops.rename({"weight":"weight_kg"},axis = 1, inplace = True)
df.to_csv('laptops.csv', index = False)
What I expected to happen:
Nice work
What actually happened:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
/dataquest/system/env/python3/lib/python3.8/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2645 try:
-> 2646 return self._engine.get_loc(key)
2647 except KeyError:
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: 'weight'
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-1-934527a212af> in <module>
49
50 new_weight = []
---> 51 for row in laptops["weight"].unique():
52 clean_weight = clean_w(row)
53 new_weight.append(clean_weight)
/dataquest/system/env/python3/lib/python3.8/site-packages/pandas/core/frame.py in __getitem__(self, key)
2798 if self.columns.nlevels > 1:
2799 return self._getitem_multilevel(key)
-> 2800 indexer = self.columns.get_loc(key)
2801 if is_integer(indexer):
2802 indexer = [indexer]
/dataquest/system/env/python3/lib/python3.8/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2646 return self._engine.get_loc(key)
2647 except KeyError:
-> 2648 return self._engine.get_loc(self._maybe_cast_indexer(key))
2649 indexer = self.get_indexer([key], method=method, tolerance=tolerance)
2650 if indexer.ndim > 1 or indexer.size > 1:
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: 'weight'
- is it necessary to create def?
- can I split the replace to 2 sentences, one for replace kg to space and another for replace kgs to space?
- why it doesn’t meed to loop the data by using “for” syntax?
4.what’s the key error"weight" mean actually?