【问题标题】:After rename column get keyerror重命名列后得到keyerror
【发布时间】:2017-09-03 15:28:11
【问题描述】:

我有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

然后将第一个值重命名为this:

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

一切看起来都很好:

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']

如果选择 b 效果很好:

print (df['b'])
0    1
1    3
2    5
Name: b, dtype: int64

但如果选择a,则返回列f

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

如果选择f 则得到keyerror。

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

print (df.info())
#KeyError: 'f'

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

【问题讨论】:

  • answer 的 cmets 中提到了这种行为。由于正在修改此索引对象的内部状态,因此它可能不会传播到使用它的所有实例。我认为使用df.rename(columns={'a': 'f'}) 是预期的方式。

标签: pandas numpy multiple-columns rename


【解决方案1】:

您不应更改 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

那是因为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

故事的寓意:以这种方式重命名列可能不是一个好主意。


但是这个故事变得更奇怪了

这很好

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

很好

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

print(df)

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

df['f']
KeyError:

事实证明,我们可以在显示df 之前修改values 属性,它显然会在第一个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

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


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)

【讨论】:

  • 非常有趣的研究!
  • 我在想print 怎么会造成这种差异。你知道为什么吗?以前没见过。
  • @jezrael 我的理论是在第一次打印时会发生初始化。
  • 不过是bug,因为print的影响?我认为这是不可能的,但也许我错了。
  • @jezrael 当 print 被调用时,它会调用 repr 方法。那时我猜熊猫会运行一些缓存脚本,如果它们以前没有运行过的话。
猜你喜欢
  • 2020-11-02
  • 2023-03-26
  • 2015-02-04
  • 1970-01-01
  • 2018-11-28
  • 2012-06-21
  • 2019-08-21
  • 2018-04-08
相关资源
最近更新 更多