Python 为什么传递元组会导致pandas中的键错误?

Python 为什么传递元组会导致pandas中的键错误?,python,pandas,Python,Pandas,我知道,若我传递一个列名列表,我可以选择多个列。我惊讶地发现我不能传递一组列名 import pandas as pd df = pd.DataFrame([[2,3,4],[3,4,5]],columns=['a','b','c']) print df[['a','b']] print df[('a','b')] # Key error 为什么会这样?我遗漏了什么重要的东西吗?就我所知,唯一的区别是第二种情况,多键是不可变的 您可以将列名设置为tuple,然后用于选择tuple: imp

我知道,若我传递一个列名列表,我可以选择多个列。我惊讶地发现我不能传递一组列名

import pandas as pd

df = pd.DataFrame([[2,3,4],[3,4,5]],columns=['a','b','c'])

print df[['a','b']]
print df[('a','b')] # Key error

为什么会这样?我遗漏了什么重要的东西吗?就我所知,唯一的区别是第二种情况,多键是不可变的

您可以将列名设置为
tuple
,然后用于选择
tuple

import pandas as pd

df = pd.DataFrame([[2,3,4],[3,4,5]],columns=[('a', 'b'),'b','c'])
print (df)
   (a, b)  b  c
0       2  3  4
1       3  4  5

print (df[('a','b')])
0    2
1    3
Name: (a, b), dtype: int64

您没有键
('a','b')
,只有
'a','b','c'
键存在

元组还用于从具有多索引的数据帧中选择列:

import pandas as pd
columns = pd.MultiIndex.from_arrays([['a','b','c'], ['X','Y','Z']])
df = pd.DataFrame([[2,3,4],[3,4,5]], columns=columns)
#    a  b  c
#    X  Y  Z
# 0  2  3  4
# 1  3  4  5
然后

元组列表选择多个列,每个元组指定一列:

In [204]: df[[('a','X'), ('b','Y')]]
Out[204]: 
   a  b
   X  Y
0  2  3
1  3  4

使用类型检查产生以下行为:

    # lists are handled here ----------------------vvvv
    if isinstance(key, (Series, np.ndarray, Index, list)):
        # either boolean or fancy integer index
        return self._getitem_array(key)
    elif isinstance(key, DataFrame):
        return self._getitem_frame(key)
    # tuples are handled here when self has a MultiIndex
    elif is_mi_columns:
        return self._getitem_multilevel(key)
    # or else here
    else:
        return self._getitem_column(key)
In [204]: df[[('a','X'), ('b','Y')]]
Out[204]: 
   a  b
   X  Y
0  2  3
1  3  4
    # lists are handled here ----------------------vvvv
    if isinstance(key, (Series, np.ndarray, Index, list)):
        # either boolean or fancy integer index
        return self._getitem_array(key)
    elif isinstance(key, DataFrame):
        return self._getitem_frame(key)
    # tuples are handled here when self has a MultiIndex
    elif is_mi_columns:
        return self._getitem_multilevel(key)
    # or else here
    else:
        return self._getitem_column(key)