2016-07-20 58 views
2

我有這種方法,根據標籤抓取pandas dataframe的列,但通過numpy索引要快得多。從pd.DataFrame獲得列標籤索引的有效方法

有沒有辦法在pandasnumpy從列標籤到列索引沒有迭代?

DF_var = pd.DataFrame(np.random.random((5,10)), columns=["attr_%d" % _ for _ in range(10)]) 
query_cols = ["attr_2","attr_5","attr_6","attr_0"] 
want_idx = [0,2,5,6] 

# Something like np.where w/o iterating through? 
# np.where(query_cols in DF_var.columns) 
# TypeError: unhashable type: 'list' 

# np.where(x in DF_var.columns for x in query_cols) 
# (array([0]),) 


long_way = list() 
for i, label in enumerate(DF_var.columns): 
    if label in query_cols: 
     long_way.append(i) 
# print(sorted(long_way)) 
# [0, 2, 5, 6] 

enter image description here

+2

參見:http://stackoverflow.com/questions/13021654/retrieving-column-index-from-column-name-in-python-pandas – albert

+0

這是爲單個值還是列表? –

+0

@ O.rka single,但你可以使用列表理解來獲得所有的索引。 – Alex

回答

2
short_way = [df.columns.get_loc(col) for col in query_cols] 
print(sorted(short_way)) 
# outputs [0, 2, 5, 6] 
+1

噢好吧,它仍然需要迭代? –

+1

@ O.rka是的。 AFAIK沒有矢量化的方式。 – Alex

+0

感謝您的反饋@Alex –