从python大 pandas 的列名中检索列索引 [英] Retrieving column index from column name in python pandas

查看:399
本文介绍了从python大 pandas 的列名中检索列索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R中,当您需要根据列的名称检索列索引时,您可以执行

In R when you need to retrieve a column index based on the name of the column you could do

idx <- which(names(my_data)==my_colum_name)

有没有办法做同样的熊猫数据帧?

Is there a way to do the same with pandas dataframes?

推荐答案

当然可以使用 .get_loc()

In [45]: df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})

In [46]: df.columns
Out[46]: Index([apple, orange, pear], dtype=object)

In [47]: df.columns.get_loc("pear")
Out[47]: 2

虽然老实说,我不经常需要这个。通常按名称访问我想要的东西( df [pear] df [[apple,orange]] / code>,或者可能 df.columns.isin([orange,pear])),虽然我可以看到你会要索引号。

although to be honest I don't often need this myself. Usually access by name does what I want it to (df["pear"], df[["apple", "orange"]], or maybe df.columns.isin(["orange", "pear"])), although I can definitely see cases where you'd want the index number.

这篇关于从python大 pandas 的列名中检索列索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆