pandas 熊猫:转换多索引数据帧中的索引类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34417970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:25:13  来源:igfitidea点击:

pandas: convert index type in multiindex dataframe

pythonpandastypesmulti-index

提问by Boosted_d16

Hi have a multiindex dataframe:

嗨,有一个多索引数据框:

tuples = [('YTA_Q3', 1), ('YTA_Q3', 2), ('YTA_Q3', 3), ('YTA_Q3', 4), ('YTA_Q3', 99), ('YTA_Q3', 96)]
# Index
index = pd.MultiIndex.from_tuples(tuples, names=['Questions', 'Values'])
# Columns
columns = pd.MultiIndex.from_tuples([('YTA_Q3', '@')], names=['Questions', 'Values'])
# Data
data = [29.014949,5.0260590000000001,
  6.6269119999999999,
  1.3565260000000001,
  41.632221999999999,
  21.279499999999999]

df1 = pd.DataFrame(data=data, index=index, columns=columns)

How do I convert the inner values of the df's index to str?

如何将 df 索引的内部值转换为 str?

My attempt:

我的尝试:

df1.index.astype(str) 

returns a TypeError

返回一个类型错误

回答by Anton Protopopov

IIUC you need the last level of Multiindex. You could access it with levels:

IIUC 你需要最后一级的 Multiindex。您可以通过以下方式访问它levels

df1.index.levels[-1].astype(str)

In [584]: df1.index.levels[-1].astype(str)
Out[584]: Index(['1', '2', '3', '4', '96', '99'], dtype='object', name='Values')

EDIT

编辑

You could set your inner level with set_levelsmethod of multiIndex:

您可以使用set_levelsmultiIndex 方法设置您的内部级别:

idx = df1.index
df1.index = df1.index.set_levels([idx.levels[:-1], idx.levels[-1].astype(str)])

回答by FuzzyDuck

I find the current pandas implementation a bit cumbersome, so I use this:

我发现当前的 Pandas 实现有点麻烦,所以我使用这个:

df1.index = pd.MultiIndex.from_tuples([(ix[0], str(ix[1])) for ix in df1.index.tolist()])

df1.index = pd.MultiIndex.from_tuples([(ix[0], str(ix[1])) for ix in df1.index.tolist()])

回答by Tajni

There was change in pandas and old way doesn't work properly.

大Pandas发生了变化,旧方式无法正常工作。

For me this worked.

对我来说这有效。

level_to_change = 1
df.index = df.index.set_levels(df.index.levels[level_to_change].astype(int), level=level_to_change)