Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
708 views
in Technique[技术] by (71.8m points)

python - pandas: convert index type in multiindex dataframe

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?

My attempt:

df1.index.astype(str) 

returns a TypeError

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

IIUC you need the last level of Multiindex. You could access it with 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_levels method of multiIndex:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...