gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:09:39 25 4
gpt4 key购买 nike

<分区>

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com