使用此處pandas找到的文檔中的示例,以下索引完美運行,結果為:pd.Seriesimport pandas as pdtuples = [(1, 'red'), (1, 'blue'), (2, 'red'), (2, 'blue')]columns = pd.MultiIndex.from_tuples(tuples, names=('number', 'color'))asdf = pd.DataFrame(columns=columns, index=[0, 1])asdf.loc[:, (1, 'red')]但是如果我稍微改變一下代碼,去掉一層,同樣的索引就不起作用了:import pandas as pdtuples = [(1,), (2,)]columns = pd.MultiIndex.from_tuples(tuples, names=['number'])asdf = pd.DataFrame(columns=columns, index=[0, 1])asdf.loc[:, (1,)]IndexError Traceback (most recent call last)<ipython-input-43-d55399a979fa> in <module>----> 1 asdf.loc[:, (1,)]/opt/conda/lib/python3.8/site-packages/pandas/core/indexing.py in __getitem__(self, key) 1760 except (KeyError, IndexError, AttributeError): 1761 pass-> 1762 return self._getitem_tuple(key) 1763 else: 1764 # we by definition only have the 0th axis/opt/conda/lib/python3.8/site-packages/pandas/core/indexing.py in _getitem_tuple(self, tup) 1270 def _getitem_tuple(self, tup: Tuple): 1271 try:-> 1272 return self._getitem_lowerdim(tup) 1273 except IndexingError: 1274 pass/opt/conda/lib/python3.8/site-packages/pandas/core/indexing.py in _getitem_lowerdim(self, tup) 1371 # we may have a nested tuples indexer here 1372 if self._is_nested_tuple_indexer(tup):-> 1373 return self._getitem_nested_tuple(tup) 1374 1375 # we maybe be using a tuple to represent multiple dimensions hereIndexError: tuple index out of range此外,將其索引為asdf.loc[:, 1]throws a TypeError,更進一步,將其索引為asdf.loc[:, ((1,),)]works ,但結果是 a pd.DataFrame,而不是pd.Series!為什么會這樣?非常感謝您!PS:我有興趣從這些問題中“抽象”我的代碼(一個級別與一個級別中的多個級別pd.DataFrame.columns)。在我工作的公司中,有時我們會獲得需要多個級別的客戶數據,但有時只需要一個級別。
1 回答

慕容708150
TA貢獻1831條經驗 獲得超4個贊
你有更新你的熊貓版本嗎?在 中pandas v1.1.0,您可以像以前一樣使用一個級別進行索引,切片返回一個pd.Series
import pandas as pd
tuples = [(1,), (2,)]
columns = pd.MultiIndex.from_tuples(tuples, names=['number'])
asdf = pd.DataFrame(columns=columns, index=[0, 1])
asdf.loc[:, (1,)]
輸出:
0 NaN
1 NaN
添加回答
舉報
0/150
提交
取消