【问题标题】:Efficient way to get indices of column-labels from pd.DataFrame [duplicate]从 pd.DataFrame [重复] 获取列标签索引的有效方法
【发布时间】:2016-11-24 03:19:39
【问题描述】:

我有这种方法,我根据标签从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]

【问题讨论】:

  • 这是针对单个值还是针对列表?
  • @O.rka single,但您可以使用列表推导来获取所有索引。
  • 这使用 numpy np.argwhere(DF_var.columns.isin(["attr_2","attr_5","attr_6","attr_0"])).flatten() 完成这项工作
  • @O.rka 你可以使用searchsorted method。新答案发布到链接的 dup 目标中。

标签: python numpy pandas indexing dataframe


【解决方案1】:
short_way = [df.columns.get_loc(col) for col in query_cols]
print(sorted(short_way))
# outputs [0, 2, 5, 6]

【讨论】:

  • 哦,好吧,所以它仍然需要迭代?
  • @O.rka 是的。 AFAIK 没有矢量化方式。
猜你喜欢
  • 2020-03-02
  • 2015-12-20
  • 2017-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-26
  • 1970-01-01
  • 2018-11-17
相关资源
最近更新 更多