如何更改“多索引熊猫”数据框中的索引值?

时间:2020-05-06 00:43:12

标签: python pandas

If you look at the above image, the level 0 index (3, 102483) are random numbers. And this goes on until the end of the dataset. I want to be able to change these numbers to be from 0,1,2,3 so on. So 3 would be 0 and so on我有一个带有多索引的数据框,我想更改其中一个的值。

例如:

index = [1,23,356,405,513,65,6787,898,679]
index_2 = ["A","B","C","D","E","F","G","H","I"]
names= ["James","Adam","Mary","Tom","Sam","Harry","Jacob","Isa","Rick"]

df_test = pd.DataFrame(data=names, index=[index, index_2])

这将为我提供一个带有两个索引的数据框。 “索引”是诸如上述的随机数。但是,我想将索引更改为默认值,以便它采用0、1、2、3等值,而不是上面的随机数。

我正在使用一个非常大的数据集对数据进行随机编号,因此我想将其更改为默认索引编号为0、1,2等。

所以我的问题是,如何用默认索引替换值?

3 个答案:

答案 0 :(得分:0)

您可以将数据长度的范围传递给索引:

range_1 = list(range(len(names)))
df_test = pd.DataFrame(data=[names], index=[range_1, index_2])

答案 1 :(得分:0)

如果df_test已经存在,则可以使用pd.MultiIndex.from_arrays设置索引,并从要替换为增量值的原始索引级别获取codes,并用get_level_values替换另一个。

# assume df_test created like this 
index = [1,1,356,356,356,6787,6787,6787,6787] #change this to be more like your problem
index_2 = ["A","B","C","D","E","A","B","C","D"]
names= ["James","Adam","Mary","Tom","Sam","Harry","Jacob","Isa","Rick"]

df_test = pd.DataFrame(data=names, index=[index, index_2])
print (df_test)
            0
1    A  James
     B   Adam
356  C   Mary
     D    Tom
     E    Sam
6787 A  Harry
     B  Jacob
     C    Isa
     D   Rick

# so you can do to have regular incremental for first level of index
df_test.index = pd.MultiIndex.from_arrays([df_test.index.codes[0], 
                                           df_test.index.get_level_values(1)])
print (df_test)
         0
0 A  James
  B   Adam
1 C   Mary
  D    Tom
  E    Sam
2 A  Harry
  B  Jacob
  C    Isa
  D   Rick

答案 2 :(得分:0)

不确定这是否是您的期望,可以直观地看到您的预期输出:

#drop the index with the random numbers
df_test = df_test.droplevel(0)
#get the indices for the letters
#assumption here is that the letters r not repeated
new_index = df_test.index.get_indexer_for(df_test.index)

#if the letters are not unique :
from itertools import chain, islice
c = chain.from_iterable
e = enumerate
#this allows us to pull the unique numbers per letter
new_index = islice(c(e(df_test.index)),0,None,2)

#assign the new index, and set it as the outermost index
df_test.set_index(new_index,append=True).swaplevel(1,0)