从python pandas中的列名获取列索引 [英] Get column index from column name in python pandas
本文介绍了从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)
有没有办法对熊猫做同样的事情dataframes?
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]]
,或者 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屋!
查看全文