嵌套字典 –> 具有多列的数据框

huangapple go评论66阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月27日 21:01:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76565146.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定