将数据从字符串转换为int时出错

时间:2018-02-19 16:20:16

标签: python pandas dataframe type-conversion

我有一个数据框cleaned_bp['VISITCODE'],如下所示:

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

其中非索引列由字符串组成。 我想通过执行以下操作将它们转换为整数:

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

但是我收到了这个错误:

    ---------------------------------------------------------------------------
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
我在这做什么错?

2 个答案:

答案 0 :(得分:1)

尝试:

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

这将使用索引中的位置而不是索引本身。

答案 1 :(得分:1)

如果你正在使用熊猫,你可以试试:

cleaned_bp.VISITCODE.astype(int)