Panda系列/数据框的重命名索引

3
为什么我可以使用 ('a','b') 重命名pandas Series中的一行,但不能使用 (1.0, 2.0)。为什么元组中值的类型会影响重命名功能?
df = pd.DataFrame({'a': [1,2,3,4,5], 'b':[1,1,1,1,1,]}).set_index('a')

df.rename(index={1:(1,2)})
*** ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
df.rename(index={1:('1','2')})
        b
a
(1, 2)  1
2       1
3       1
4       1
5       1

我非常希望能够将其保留为整数/浮点数。


我的pandas版本是:'0.14.1'。 - Rambatino
当前版本为0.17.1。你能否升级并再次尝试呢? - DSM
我不确定能否升级。公司在pandas 0.14.1的基础上构建了很多架构,升级很可能会破坏其中很多内容。这个版本没有其他解决方法吗?我会阅读版本说明。 - Rambatino
很遗憾,由于我无法重现这个问题,所以我无法测试任何我可能建议的解决方法。希望其他人能够提供帮助。 - DSM
好的,谢谢@DSM,我会考虑更新。 - Rambatino
1个回答

1
我不确定为什么不能使用 rename 完成,但您可以在列表中创建整数或浮点数元组,然后将结果分配给索引。

这在 Pandas 0.14.1 中有效:

idx = [(1, 2), 2, 3, 4, 5]
df.index = idx
>>> df
        b
(1, 2)  1
2       1
3       1
4       1
5       1

编辑 这里是一个包含 500k 行数据框的时间比较。

import numpy as np
import pandas as pd

df = pd.DataFrame({'a': [1,2,3,4,5]*100000, 'b':[1,1,1,1,1,]*100000})
# Create 100k random numbers in the range of the index.
rn = np.random.random_integers(0, 499999, 100000)

# Normal lookup using `loc`.
>>> %%timeit -n 3 some_list = []
    [some_list.append(df.loc[a]) for a in rn]
3 loops, best of 3: 6.63 s per loop

# Normal lookup using 'xs' (used only for getting values, not setting them).
>>> %%timeit -n 3 some_list = []
    [some_list.append(df.xs(a)) for a in rn]
3 loops, best of 3: 4.46 s per loop 

# Set the index to tuple pairs and lookup using 'xs'.
idx = [(a, a + 1) for a in np.arange(500000)]
df.index = idx
>>> %%timeit -n 3 some_list = []
    [some_list.append(df.xs((a, a + 1))) for a in rn]
3 loops, best of 3: 4.64 s per loop

正如您所看到的,从数据框中查找值时性能差异微不足道。
请注意,您不能使用元组索引与 'loc'。
>>> df.loc[(1, 2)]
KeyError: 'the label [1] is not in the [index]'

真的。我猜解决方法是:如果x==1,则df.index = [(1,2) else x for x in df.index],因为那只是样本数据,实际上是一个有许多重复元素的大型数据集。然而,这种解决方法会破坏性能:( - Rambatino
你确定它会影响性能吗?你测试过了吗? - Alexander
索引不是散列的吗?如果将索引转换为数组,然后循环遍历更改它们然后重新插入,那么这不会破坏它们被散列的事实吗? - Rambatino
我认为当你替换索引时哈希表会被重建。请看一下我的编辑中的时间比较。 - Alexander

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接