'The above exception was the direct cause of the following exception:?

I am working on a dataset that has a column of Airbags, type: pandas.core.series.Series.

Airbags Column:

Airbags Column

I want to find the number of airbags rather than their position, so I ran the following code:

type(data['Airbags'])
data['Airbags'] = data['Airbags'].replace(np.nan, '0')
len(data['Airbags'][1].split(','))     #gives correct output

But when I ran a loop to do this for the entire column:

 for i in range(1198):
  if(data['Airbags'][i]=='0'):
   data['Airbags_count'][i]=0
  else:
   data['Airbags_count'][i]=len(data['Airbags'][i].split(','))

I get this error: KeyError: 252

ERROR

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

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.7/dist-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:

My goal is to get the count of the airbags. If anyone has another approach or a solution to this problem, I would be grateful.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source