从pd.DataFrame获取列标签索引的有效方法

时间:2016-07-20 19:04:49

标签: python numpy pandas indexing dataframe

我有这种方法,我根据标签从pandas dataframe抓取列,但通过numpy索引要快得多。

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

1 个答案:

答案 0 :(得分:2)

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