gpt4 book ai didi

python - 将多级多索引名称转换为 DataFrame 列,Python 3.6

转载 作者:太空宇宙 更新时间:2023-11-04 02:03:23 25 4
gpt4 key购买 nike

数据列:

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

最佳答案

使用 mapjoin:

Data.columns = Data.columns.map('|'.join)

或者列表理解:

Data.columns = [f'{a}{b}' for a, b in Data.columns]

关于python - 将多级多索引名称转换为 DataFrame 列,Python 3.6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55263408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com