python 如何根据列名获取所在列的位置

 时间:2026-02-12 23:33:04

1、首先导入包

import numpy as np

import pandas as pd

2、###生成一个datdaframe ,用于测试

df = pd.DataFrame({'key1':list('aabba'),'key2':['one','two','one','two','one'],'data1':np.random.randn(5),'data2':np.random.randn(5)})

print(df)

3、column 为列名的列表

column=list(df.columns)

####index

print(column)

4、测试列明“key1”

###

print(column.index('key1'))

5、下面就是结果啦

"H:\Program Files\Anaconda3\python.exe" H:/Local/python/mycode/linshi

      data1     data2 key1 key2

0 -0.942701  0.791510    a  one

1 -2.009898 -0.653434    a  two

2 -1.888589  0.405016    b  one

3 -0.863688  0.963135    b  two

4  0.444802  0.388440    a  one

['data1', 'data2', 'key1', 'key2']

2

Process finished with exit code 0

6、2 即为位置 (从0开始) 顺利得到

python 如何根据列名获取所在列的位置

7、index() 函数用于从列表中找出某个值第一个匹配项的索引位置。

感谢实验室小伙伴温、涛提供的方法

  • 数据展示工具FineBI中的多路径表间关联关系
  • excel怎样快速删除不完整数据
  • 一次性将表格区域所有空单白元格填充为数字0
  • 如何在EXCEL里找到想要的资料
  • 如何快速获取一列单元格中的指定元素
  • 热门搜索
    复试一般问什么问题 physx是什么 1987年是什么命 乳糖不耐受是什么意思 什么手什么脚 泡打粉是什么 什么是上层建筑 99朵玫瑰代表什么意思 公益性岗位是什么 破壁机什么牌子好