在Pandas中使用DataFrame.ix和元组索引

3 投票
2 回答
3013 浏览
提问于 2025-04-18 18:23

我有一段使用Pandas的代码,这段代码用元组作为索引。最近,我需要用DataFrame.ix来访问一个DataFrame中的单个元素,但它对元组有些困惑。它似乎把我的元组当成了一系列的键,认为我想访问多个值,而不是把元组当作一个单独的键(虽然这个键是一个序列)。我该如何提取一个以元组为键的单独行呢?

也许这是一个警示,提醒大家在Pandas的索引中不要使用序列,但对我来说,已经来不及了。

import string, pandas as pd, numpy as np

bar = pd.DataFrame(np.random.random((8,2)))
bar.columns = ['col1', 'col2']
bar.index = list(string.ascii_lowercase)[:8]
print bar
print bar.iloc[0].name
print bar.ix[bar.iloc[0].name]

bar.index = [tuple(list(string.ascii_lowercase)[i:i+3]) for i in range(8)]
print bar.iloc[0].name
print bar.ix[bar.iloc[0].name] # Fails with `KeyError: 'a'`

2 个回答

3

我觉得用索引的方法可能做不到,但你可以用 xs 来实现:

>>> bar.xs(bar.iloc[0].name)
col1    0.864788
col2    0.708136
Name: (a, b, c), dtype: float64
6

你可以把这个元组放在一个列表里,这样就能让它正常工作了。

In [17]: bar.ix[[bar.iloc[0].name]]
Out[17]: 
               col1      col2
(a, b, c)  0.216689  0.262511

撰写回答