将字符串值转换为Pandas中的整数值

时间:2019-10-17 01:04:32

标签: python pandas

我正在研究为给定列将字符串值转换为整数的函数。函数如下:

def turn_to_int(value):
    if value == 'Younger than 5 years':
        return 5
    elif value == 'Older than 85':
        return 85
    else:
        pass

但是,每当尝试使用map或apply函数时,我都会收到一条错误消息:

survey_strip_up = survey_strip['Age1stCode'].apply(turn_to_int)

这两个值肯定存在,但是我得到此错误代码:

    KeyError                                  Traceback (most recent call last)
<ipython-input-14-c000da272bb4> in <module>
      7         pass
      8 
----> 9 survey_strip_up = survey_strip['Age1stCode'].apply(turn_to_int)

~\Anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    866         key = com.apply_if_callable(key, self)
    867         try:
--> 868             result = self.index.get_value(self, key)
    869 
    870             if not is_scalar(result):

~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key)
   4373         try:
   4374             return self._engine.get_value(s, k,
-> 4375                                           tz=getattr(series.dtype, 'tz', None))
   4376         except KeyError as e1:
   4377             if len(self) > 0 and (self.holds_integer() or self.is_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/index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()

KeyError: 'Age1stCode'

任何人都可以提供帮助吗?

1 个答案:

答案 0 :(得分:0)

您可以将字典映射到该列。重新分配给相同的列名以覆盖,或者(就像我通常所做的那样)在同一df中创建一个新的映射列:

d = {'Younger than 5 years': 5, 'Older than 85': 85}
survey_strip['new_col'] = survey_strip['Age1stCode'].map(d)