我正在尝试重新创建这个多索引数据框,以帮助我运行一些测试但是我正在努力。每个轴上有2个级别。它必须看起来像这样,数据框中的值并不重要,但结构是。
Question YTA_Q3
Values @
Question Values
YTA_Q3 1 29.014949
2 5.026059
3 6.626912
4 1.356526
99 41.632222
96 21.279500
索引和列返回:
df.index
Question Values
YTA_Q3 1
2
3
4
99
96
df.columns
Question Values
YTA_Q3 @
我的尝试:
l = [['q3','1',99],['q3','2',11],['q3','3',105],['q3','4',97],['q3','99',97],['q3','96',97]]
df = pd.DataFrame(l,columns = ['question','values','@'])
df.set_index(['question'],inplace=True)
df
values @
question
q3 1 99
q3 2 11
q3 3 105
q3 4 97
q3 99 97
q3 96 97
答案 0 :(得分:2)
这是构建预期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]
df = pd.DataFrame(data=data, index=index, columns=columns)
print(df)
Questions YTA_Q3
Values @
Questions Values
YTA_Q3 1 29.014949
2 5.026059
3 6.626912
4 1.356526
99 41.632222
96 21.279500