gpt4 book ai didi

python - 合并后列上的 Pandas 多重索引

转载 作者:行者123 更新时间:2023-12-02 01:24:18 24 4
gpt4 key购买 nike

我创建了这个数据框:

d1 = {'john': [10, 11], 'adam': [20,21]}
d2 = {'john': [1,12], 'adam': [3,34]}
test_df1= pd.DataFrame(data=d1)
test_df2= pd.DataFrame(data=d2)

current = pd.concat([test_df1, test_df2], keys=['test_df1','test_df2'], axis=1)
current

enter image description here

但我需要更改列多重索引中的顺序。我需要这样的东西

data = {('John', 'test_df1'): [10, 11], ('John', 'test_df2'): [1, 12], ('Adam', 'test_df1'): [20, 21], ('Adam','test_df2'): [3,34]}
columns = pd.MultiIndex.from_tuples([('John', 'test_df1'),('John', 'test_df2'),('Adam', 'test_df1'),('Adam', 'test_df2')])
needed = pd.DataFrame(data, columns=columns)
needed

enter image description here

你能帮我吗:)?

最佳答案

concat在另一个轴上,和 unstack :

pd.concat([test_df1, test_df2], keys=['test_df1','test_df2']).unstack(0)

输出:

      john              adam         
test_df1 test_df2 test_df1 test_df2
0 10 1 20 3
1 11 12 21 34

关于python - 合并后列上的 Pandas 多重索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75160137/

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