Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 多索引数据帧_Python_Pandas_Multi Index - Fatal编程技术网

Python 多索引数据帧

Python 多索引数据帧,python,pandas,multi-index,Python,Pandas,Multi Index,我有一个带元组键的字典,我想用多索引制作dataframe: dct = {('a', 'b'): 1, ('a', 'c'): 2} pd.DataFrame(dct, index=['x']) 它返回: 但当我把这张单子列出来的时候: dct = {('a', 'b'): 1, ('a', 'c'): 2} pd.DataFrame([dct, dct], index=['x', 'y']) 它返回: 如何使用此代码嵌套索引 即它应该返回: 你不能简单地用一系列口述来达到你的目的。如

我有一个带元组键的字典,我想用多索引制作dataframe:

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

但当我把这张单子列出来的时候:

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

如何使用此代码嵌套索引

即它应该返回:

你不能简单地用一系列口述来达到你的目的。如果只是重复使用字典,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
如果要在数据帧中的每一行中使用不同的值,则应在字典中这样做:

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