【问题标题】:Rename index of Panda Series/DataFrame重命名 Pandas Series/DataFrame 的索引
【发布时间】:2016-02-28 18:04:53
【问题描述】:

为什么我可以用 ('a','b') 而不是 (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

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

【问题讨论】:

  • 我的熊猫版本是:'0.14.1'
  • 当前版本为0.17.1。您可以升级并重试吗?
  • 我不确定我是否可以升级。该公司在 pandas 0.14.1 之上构建了很多架构,升级很可能会破坏很多架构。当前版本没有解决方法吗?我会阅读版本说明。
  • 可能,但不幸的是,由于我无法重现该问题,我无法测试我可能提出的任何建议是否有效。希望其他人可以提供帮助。
  • 好的,谢谢@DSM,我会考虑更新

标签: python pandas dataframe rename series


【解决方案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]'

【讨论】:

  • 是的。我想解决方法是: df.index = [(1,2) if x==1 else x for x in df.index] 因为这只是样本数据,它实际上是一个包含许多重复元素的大型数据集。但是,这种解决方法会破坏性能:(
  • 你确定它会破坏性能吗?你计时了吗?
  • 索引没有散列吗?因此,如果您将索引转换为数组,然后循环更改它们然后重新插入,这不会破坏它们被散列的事实吗?
  • 我相信当你替换索引时会重建哈希表。看看我的编辑中的时间比较。
猜你喜欢
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
  • 2018-08-22
  • 1970-01-01
  • 2021-05-23
  • 2019-08-18
相关资源
最近更新 更多