Huzo
Huzo

Reputation: 1692

Error in converting datas from string to int

I have a dataframe cleaned_bp['VISITCODE'] which looks like:

0          1
1          2
2          3
3          6
4          9
5         12
6         15

where the non-index column consists of strings. I wanted to convert them to integers by doing:

for i in range(len(cleaned_bp['VISITCODE'])):
    cleaned_bp['VISITCODE'][i] = int(cleaned_bp['VISITCODE'][i])

but I get this error:

    ---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-42-4d6508c1abda> in <module>()
      1 for i in range(len(cleaned_bp['VISITCODE'])):
----> 2     cleaned_bp['VISITCODE'][i] = int(cleaned_bp['VISITCODE'][i])

~/anaconda3/lib/python3.6/site-packages/pandas/core/series.py in __getitem__(self, key)
    599         key = com._apply_if_callable(key, self)
    600         try:
--> 601             result = self.index.get_value(self, key)
    602 
    603             if not is_scalar(result):

~/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_value(self, series, key)
   2475         try:
   2476             return self._engine.get_value(s, k,
-> 2477                                           tz=getattr(series.dtype, 'tz', None))
   2478         except KeyError as e1:
   2479             if len(self) > 0 and self.inferred_type in ['integer', 'boolean']:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()

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: 13

what wrong am I doing here?

Upvotes: 0

Views: 266

Answers (2)

aurelionog
aurelionog

Reputation: 11

if you are using pandas you can try:

cleaned_bp.VISITCODE.astype(int)

Upvotes: 1

joaoavf
joaoavf

Reputation: 1383

Try:

for i in range(len(cleaned_bp['VISITCODE'])):
    cleaned_bp['VISITCODE'].iloc[i] = int(cleaned_bp['VISITCODE'].iloc[i])

This will use the position in the index not the index itself.

Upvotes: 1

Related Questions