将字符串值转换为整数

2024-04-23 13:32:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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'

有人能帮忙吗


Tags: tokey函数inselfpandasgetindex
1条回答
网友
1楼 · 发布于 2024-04-23 13:32:53

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

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

相关问题 更多 >