2014-01-21 42 views
1

給定列表的索引和列,可以使用lookup()方法輕鬆地拉出熊貓DataFrame的元素。有沒有辦法從給定的數據框中獲取有序的索引和列列表(例如,在應用布爾操作之後)?清楚的是,我需要索引和列的名稱,而不僅僅是它們的整數位置。pandas逆向查找:獲取行列名稱的有序列表

這是我想出來的最接近的,雖然這是一個有點扭曲:

In [137]: df = pandas.DataFrame({"a":range(3), "b":range(10,13), "c":range(20,23)}, index=list("ABC")) 

In [138]: df 
Out[138]: 
    a b c 
A 0 10 20 
B 1 11 21 
C 2 12 22 

In [139]: df % 3 == 0 
Out[139]: 
     a  b  c 
A True False False 
B False False True 
C False True False 

In [140]: numpy.where(df % 3 == 0) 
Out[140]: (array([0, 1, 2]), array([0, 2, 1])) 

In [141]: iindices, icolumns = numpy.where(df % 3 == 0) 

In [142]: indices = df.index[iindices] 

In [143]: columns = df.columns[icolumns] 

我在尋找的結果是:

In [144]: indices, columns 
Out[144]: 
(Index([u'A', u'B', u'C'], dtype='object'), 
Index([u'a', u'c', u'b'], dtype='object')) 

替代形式更容易看通過眼:

In [145]: zip(indices, columns) 
Out[145]: [('A', 'a'), ('B', 'c'), ('C', 'b')] 

(H/T Python - find integer index of rows with NaN in pandas

+0

這裏有一個類似的問題(如與DSM的下方有類似的反應:http://stackoverflow.com/questions/20935264/finding-bogus-data-in-a-pandas-dataframe/20936428#20936428 –

+0

這就像[COO格式](https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(首席運營官)) :將dataframe(/ matrix)表示爲'(row-name,column-name,value)'的元組列表,除了這裏你不需要'value'。你可以請編輯你的標題更準確嗎? – smci

回答

4

如何:

>>> s = df.stack() 
>>> s[s % 3 == 0].index.tolist() 
[('A', 'a'), ('B', 'c'), ('C', 'b')] 

步驟一步,首先我們棧:

>>> s = df.stack() 
>>> s 
A a  0 
    b 10 
    c 20 
B a  1 
    b 11 
    c 21 
C a  2 
    b 12 
    c 22 
dtype: int64 

選擇:

>>> s % 3 == 0 
A a  True 
    b False 
    c False 
B a False 
    b False 
    c  True 
C a False 
    b  True 
    c False 
dtype: bool 

使用此過濾系列:

>>> s[s % 3 == 0] 
A a  0 
B c 21 
C b 12 
dtype: int64 

獲取指數:

>>> s[s % 3 == 0].index 
MultiIndex(levels=[[u'A', u'B', u'C'], [u'a', u'b', u'c']], 
      labels=[[0, 1, 2], [0, 2, 1]]) 

我們正在尋找的值:

>>> s[s % 3 == 0].index.tolist() 
[('A', 'a'), ('B', 'c'), ('C', 'b')]