简体   繁体   English

带有 MultiIndex 的 Pandas 数据框

[英]Pandas dataframe with MultiIndex

I have a dictionary with tuple key, and I want to make dataframe with multi index:我有一个带元组键的字典,我想用多索引制作数据框:

dct = {('a', 'b'): 1, ('a', 'c'): 2}
pd.DataFrame(dct, index=['x'])

It returns:它返回: 在此处输入图片说明

But when I put list of dicts:但是当我列出字典时:

dct = {('a', 'b'): 1, ('a', 'c'): 2}
pd.DataFrame([dct, dct], index=['x', 'y'])

It returns:它返回: 在此处输入图片说明

How do I keep indices nested using this code?如何使用此代码保持索引嵌套?

Ie it should returns:即它应该返回: 在此处输入图片说明

you can simply not use a list of dicts to achieve your result.你不能简单地使用字典列表来实现你的结果。 If the dictionary is simply just going to be repeated, pandas will do this automatically:如果只是简单地重复字典,pandas 会自动执行此操作:

dct = {('a', 'b'): 1, ('a', 'c'): 2}
df = pd.DataFrame(dct, index=['x', 'y'])

print(df)
   a   
   b  c
x  1  2
y  1  2

If you want a different value in each row if your dataframe, you should do so within your dictionary:如果您希望在数据框的每一行中使用不同的值,则应在字典中执行此操作:

dct = {('a', 'b'): [1, 3], ('a', 'c'): [2, 4]}
df = pd.DataFrame(dct, index=['x', 'y'])

print(df)
   a   
   b  c
x  1  2
y  3  4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM