英文:
nested dictionary --> dataframe with multi - columns
问题
kdict = {'A': {'a': 1, 'b': 2}, 'B': {'a': 3, 'b': 4}, 'C': {'a': 5, 'b': 6}}
df5 = pd.DataFrame.from_dict(kdict, orient='index').stack()
df5.columns = ['a', 'b', 'a', 'b', 'a', 'b']
print(df5)
英文:
kdict = {'A': {'a': 1, 'b': 2}, 'B': {'a': 3, 'b': 4}, 'C': {'a': 5, 'b': 6}}
df5 = pd.DataFrame.from_dict(kdict, orient='index').stack()
df5.columns = ['a', 'b', 'a', 'b', 'a', 'b']
print(df5)
but i want to get the result, as below --
how can i get this form, as above ?
答案1
得分: 1
你可以在重置索引后使用 pivot_table
:
import pandas as pd
kdict = {'A': {'a': 1, 'b': 2}, 'B': {'a': 3, 'b': 4}, 'C': {'a': 5, 'b': 6}}
df5 = pd.DataFrame.from_dict(kdict, orient='index').stack()
print(df5.reset_index().pivot_table(columns=['level_0', 'level_1']))
输出结果:
level_0 A B C
level_1 a b a b a b
0 1 2 3 4 5 6
英文:
You can use pivot_table
after resetting your index:
import pandas as pd
kdict = {'A': {'a': 1, 'b': 2}, 'B': {'a': 3, 'b': 4}, 'C': {'a': 5, 'b': 6}}
df5 = pd.DataFrame.from_dict(kdict, orient='index').stack()
print(df5.reset_index().pivot_table(columns=['level_0', 'level_1']))
Output:
level_0 A B C
level_1 a b a b a b
0 1 2 3 4 5 6
答案2
得分: 0
你可以尝试将Series转换为DataFrame并进行转置:
print(df5.to_frame().T)
输出:
A B C
a b a b a b
0 1 2 3 4 5 6
英文:
You can try to convert the Series to DataFrame and transpose:
print(df5.to_frame().T)
Prints:
A B C
a b a b a b
0 1 2 3 4 5 6
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论