gpt4 book ai didi

python - 重命名 Pandas 数据框的索引

转载 作者:太空狗 更新时间:2023-10-30 00:50:55 24 4
gpt4 key购买 nike

我有一个 pandas 数据框,其索引如下所示:

df.index
['a_1', 'b_2', 'c_3', ... ]

我想将这些索引重命名为:

['a', 'b', 'c', ... ]

如何在不为每个索引值指定带有显式键的字典的情况下执行此操作?
我试过:

df.rename( index = lambda x: x.split( '_' )[0] )

但这会引发错误:

AssertionError: New axis must be unique to rename

最佳答案

也许您可以通过使用 MultiIndex 来两全其美:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.arange(8).reshape(4,2), index=['a_1', 'b_2', 'c_3', 'c_4'])
print(df)
# 0 1
# a_1 0 1
# b_2 2 3
# c_3 4 5
# c_4 6 7

index = pd.MultiIndex.from_tuples([item.split('_') for item in df.index])
df.index = index
print(df)
# 0 1
# a 1 0 1
# b 2 2 3
# c 3 4 5
# 4 6 7

这样,您可以根据索引的第一级访问事物:

In [30]: df.ix['c']
Out[30]:
0 1
3 4 5
4 6 7

或者根据索引的两个级别:

In [31]: df.ix[('c','3')]
Out[31]:
0 4
1 5
Name: (c, 3)

此外,所有 DataFrame 方法都是为与具有 MultiIndices 的 DataFrame 一起工作而构建的,因此您不会有任何损失。

但是,如果你真的想删除索引的第二级,你可以这样做:

df.reset_index(level=1, drop=True, inplace=True)
print(df)
# 0 1
# a 0 1
# b 2 3
# c 4 5
# c 6 7

关于python - 重命名 Pandas 数据框的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16591923/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com