Data。列:
MultiIndex(levels=[['PDARS1M', 'PDARS1Y', 'PDKRW1M'], ['EB', 'EO', 'ER']],
labels=[[2, 0, 1, 2, 0, 1, 2, 0, 1], [0, 0, 0, 2, 2, 2, 1, 1, 1]],
names=['Instrument', 'Field'])
数据:
PDKRW1M PDARS1M PDARS1Y PDKRW1M PDARS1M PDARS1Y PDKRW1M PDARS1M PDARS1Y
EB EB EB ER ER ER EO EO EO
1125 40 53 1126 40 53 1127 40 54
1125 41 54 1126 41 54 1127 41 55
1126 41 54 1127 41 54 1128 41 55
我想合并 Data.columns.levels [0] 和 Data.columns.levels [1] ,并更新为Data.columns
我使用了以下脚本,但出现了错误
Data.columns = Data.columns.levels[0] + '|' + Data.columns.levels[1]
"ValueError: Length mismatch: Expected axis has 9 elements, new values have 3 elements"
预期数据列名称:
PDKRW1M|EB, PDARS1M|EB, PDARS1Y|EB, PDKRW1M|ER, PDARS1M|ER, PDARS1Y|ER, PDKRW1M|EO, PDARS1M|EO, PDARS1Y|EO
答案 0 :(得分:2)
将map
与join
一起使用:
Data.columns = Data.columns.map('|'.join)
或列表理解:
Data.columns = [f'{a}{b}' for a, b in Data.columns]