您有一个多索引数据框:
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)
如何将df索引的内部值转换为str?
我的尝试:
df1.index.astype(str)
返回TypeError
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')
编辑
您可以使用set_levels
multiIndex方法设置内部级别:
idx = df1.index df1.index = df1.index.set_levels([idx.levels[:-1], idx.levels[-1].astype(str)])