python - 从python pandas中的列名获取列索引

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

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

有没有办法对 pandas 数据帧做同样的事情?

最佳答案

当然,你可以使用 .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"])),虽然我绝对可以看到你想要索引号的情况。

https://stackoverflow.com/questions/13021654/

相关文章:

linux - 如何让maven构建平台独立?

mysql - 复制整个 MySQL 数据库

python - 值错误 : setting an array element with a seq

python - 如何检查字符串中的特定字符?

linux - 亚马逊 Linux : "apt-get: command not found"

python - 在 Python 中构建完整路径文件名

python - Python 3's "函数注释有什么用?

python - 如何前向声明一个函数以避免后面定义的函数出现 `NameError` s?

linux - 检查目录是否用 bash 挂载

python - boto3 客户端 NoRegionError : You must specif