重命名列后得到keyerror

jez*_*ael 13 numpy rename multiple-columns pandas

我有df:

df = pd.DataFrame({'a':[7,8,9],
                   'b':[1,3,5],
                   'c':[5,3,6]})

print (df)
   a  b  c
0  7  1  5
1  8  3  3
2  9  5  6
Run Code Online (Sandbox Code Playgroud)

然后通过重命名第一个值这个:

df.columns.values[0] = 'f'
Run Code Online (Sandbox Code Playgroud)

一切似乎都很好:

print (df)
   f  b  c
0  7  1  5
1  8  3  3
2  9  5  6

print (df.columns)
Index(['f', 'b', 'c'], dtype='object')

print (df.columns.values)
['f' 'b' 'c']
Run Code Online (Sandbox Code Playgroud)

如果选择b它很好:

print (df['b'])
0    1
1    3
2    5
Name: b, dtype: int64
Run Code Online (Sandbox Code Playgroud)

但如果选择a它返回列f:

print (df['a'])
0    7
1    8
2    9
Name: f, dtype: int64
Run Code Online (Sandbox Code Playgroud)

如果选择f得到keyerror.

print (df['f'])
#KeyError: 'f'

print (df.info())
#KeyError: 'f'
Run Code Online (Sandbox Code Playgroud)

有什么问题?有人可以解释一下吗?还是虫子?

piR*_*red 21

您不应该更改该values属性.

试试看df.columns.values = ['a', 'b', 'c'],你得到:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-61-e7e440adc404> in <module>()
----> 1 df.columns.values = ['a', 'b', 'c']

AttributeError: can't set attribute
Run Code Online (Sandbox Code Playgroud)

那是因为pandas检测到您正在尝试设置属性并阻止您.

但是,它无法阻止您更改底层values对象本身.

当你使用时rename,pandas跟进一堆清理的东西.我已粘贴下面的来源.

最终你所做的就是在不启动清理的情况下改变数值.您可以通过后续调用_data.rename_axis自行启动它(示例可以在下面的源代码中看到).这将强制清理运行然后您可以访问['f']

df._data = df._data.rename_axis(lambda x: x, 0, True)
df['f']

0    7
1    8
2    9
Name: f, dtype: int64
Run Code Online (Sandbox Code Playgroud)

故事的道德:以这种方式重命名专栏可能不是一个好主意.


但这个故事更加怪异

这可以

df = pd.DataFrame({'a':[7,8,9],
                   'b':[1,3,5],
                   'c':[5,3,6]})

df.columns.values[0] = 'f'

df['f']

0    7
1    8
2    9
Name: f, dtype: int64
Run Code Online (Sandbox Code Playgroud)

这是罚款

df = pd.DataFrame({'a':[7,8,9],
                   'b':[1,3,5],
                   'c':[5,3,6]})

print(df)

df.columns.values[0] = 'f'

df['f']
Run Code Online (Sandbox Code Playgroud)
KeyError:
Run Code Online (Sandbox Code Playgroud)

事实证明,我们可以values在显示之前修改属性df,它显然会在第一个上运行所有初始化display.如果在更改values属性之前显示它,则会出错.

我们还在

df = pd.DataFrame({'a':[7,8,9],
                   'b':[1,3,5],
                   'c':[5,3,6]})

print(df)

df.columns.values[0] = 'f'

df['f'] = 1

df['f']

   f  f
0  7  1
1  8  1
2  9  1
Run Code Online (Sandbox Code Playgroud)

好像我们还不知道这是一个坏主意......


来源 rename

def rename(self, *args, **kwargs):

    axes, kwargs = self._construct_axes_from_arguments(args, kwargs)
    copy = kwargs.pop('copy', True)
    inplace = kwargs.pop('inplace', False)

    if kwargs:
        raise TypeError('rename() got an unexpected keyword '
                        'argument "{0}"'.format(list(kwargs.keys())[0]))

    if com._count_not_none(*axes.values()) == 0:
        raise TypeError('must pass an index to rename')

    # renamer function if passed a dict
    def _get_rename_function(mapper):
        if isinstance(mapper, (dict, ABCSeries)):

            def f(x):
                if x in mapper:
                    return mapper[x]
                else:
                    return x
        else:
            f = mapper

        return f

    self._consolidate_inplace()
    result = self if inplace else self.copy(deep=copy)

    # start in the axis order to eliminate too many copies
    for axis in lrange(self._AXIS_LEN):
        v = axes.get(self._AXIS_NAMES[axis])
        if v is None:
            continue
        f = _get_rename_function(v)

        baxis = self._get_block_manager_axis(axis)
        result._data = result._data.rename_axis(f, axis=baxis, copy=copy)
        result._clear_item_cache()

    if inplace:
        self._update_inplace(result._data)
    else:
        return result.__finalize__(self)
Run Code Online (Sandbox Code Playgroud)

  • 非常有趣的研究! (3认同)
  • 我正在考虑“打印”如何导致这种差异。你知道为什么吗?以前没看过。 (2认同)